简单了解Object.defineproperty

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty 这个是链接
let obj = {name: 123}

var value = ''

Object.defineProperty(obj, 'name', {

get: function () {

return 'get' + value

},

set: function (newVlaue) {

value = newVlaue

console.log('set', value)

}

})

obj.name = 'zs'

console.log(obj)

// 这是一个好看的分割线~~~~~~~~~~

因为数组没有办法被object.defineProperty做监听,但是数组的prototype原型是一个object,所以可以监听数组原型上的push方法,下面是不改变数组原有的push方法在上面增加一个console.log

var arrayPrototype = Object.create(Array.prototype)

console.log(arrayPrototype)

Object.defineProperty(arrayPrototype, 'push', {

value: function() {

console.log('add console.log to push')

}

})

let arr = [1,2]

arr.__proto__ = arrayPrototype

console.log(arr)

arr.push(3)


yellowDog
28 声望3 粉丝