Object.definedproperty Can add a property to an Object, or modify an existing property to add configuration items
parameter
Const obj = {} /** * obj source object * prop The name or Symbol of the property to define or modify. * descriptor Property descriptor to define or modify. DefineProperty (obj, 'a', {value: 1, // cx: 64x) // The descriptor of this property can be changed and deleted from the corresponding object only if and when the property's key is set to true. The default is false. Writable: true, // whether writable. The default is false Enumerable: true, // This property appears in the object's enumerable properties if and only if the property's Enumerable key is true. Get () {}, set() {}, set() {})Copy the code
‘get xx attr’ ‘set xx attr’ ‘set xx attr’
var object = { a: 1, b: 2 } for(let key in object) { let value = obj[key] Object.defineProperty(object, key, { configurable: true, enumerable: true, get() { console.log(`get ${key} attr`) return value }, set(newValue) { console.log(`set ${key} attr`) value = newValue } }) } object.a // get a attr object.b = 3 // ser a Atter does not trigger get when setting valuesCopy the code
The get method is not triggered when setting a value
Implement a vUe-like responsive proxy
$data.a = this.$data.a = this.$data.a
var Vue = {
$data: {
a: 1,
b: 2
}
}
for(let key in Vue.$data) {
let value = Vue.$data[key]
Object.defineProperty(Vue, key, {
configurable: true,
enumerable: true,
get() {
return Vue.$data[key]
},
set(newValue) {
Vue.$data[key] = newValue
}
})
}
console.log(Vue.a, Vue.$data.a) // 1, 1
Vue.a = 2
console.log(Vue.a, Vue.$data.a) // 2, 2
Vue.$data.b = 3
console.log(Vue.b, Vue.$data.b) // 3, 3
Copy the code
Simple realization of Vue on the array of hijacking processing
var arr = [1, {a: 1}, 3] for (var i = 0; i < arr.length; i++) { if (typeof arr[i] === 'object' && arr[i] ! == null) { for (let key in arr[i]) { let value = arr[i][key] Object.defineProperty(arr[i], key, { configurable: true, enumerable: true, get() { console.log(`get ${key} attr`) return value }, Set (newValue) {console.log(' set ${key} attr ') value = newValue}})}} // arrPro Var arrPro = object.create (array.prototype) arr.__proto__ = arrPro const push = arrPro.push arrPro.push = function(argu) { if (typeof argu === 'object' && argu ! == null) { for (let key in argu) { let value = argu[key] Object.defineProperty(argu, key, { configurable: true, enumerable: true, get() { console.log(`get ${key} attr`) return value }, set(newValue) { console.log(`set ${key} attr`) value = newValue } }) } } push.call(this, Argu)} arr[0] = 0 arr[1]. A = 'a' // Make the added data responsive arr. Push ({b: 2})Copy the code
[Notes are not easy, if it is helpful to you, please like, thank you]