let numbers = [0, 1, 2];
numbers = new Proxy(numbers, {
get(target, prop) {
return target[prop] ? target[prop] : 0;
},
set(target, prop, value) {
if (typeof value === 'number') {
target[prop] = value;
return true;
} else {
return false;
}
},
});
numbers[4] = 4;
// numbers[9] = '9'; //Error: 'set' on proxy: trap returned falsish for property '9'
console.log(numbers[1]);
console.log(numbers[78]);
let numbers = [0, 1, 2];
numbers = new Proxy(numbers, {
get(target, prop) {
return Reflect.get(target, prop);
},
set(target, prop, value) {
if (typeof value === 'number') {
Reflect.set(target, prop, value);
return true;
} else {
return false;
}
},
});
numbers[4] = 4;
console.log(numbers[1]);
console.log(numbers[4]);
// 一个属性不能同时数据属性和
let _name = 'sfd';
let A = {
get name() {
return _name;
},
set name(name) {
_name = name;
this.getName();
},
getName: function () {
console.log(this.name);
},
};
A.name = 8080;
const A = {
getName: function () {
console.log(this.name);
},
};
Object.defineProperty(A, 'name', {
set(value) {
this._name = value;
this.getName();
},
get() {
return this._name;
},
});
A.name = 'Joy';
const _A = {
name: 'sfd',
getName: function () {
console.log(this.name);
},
};
const A = new Proxy(_A, {
get(target, prop) {
return Reflect.get(target, prop);
},
set(target, prop, value) {
Reflect.set(target, prop, value);
target.getName();
return true;
},
});
A.name = 'Joy';