JavaScript | handler.deleteProperty() 方法
JavaScript 中的handler.deleteProperty()方法是删除运算符的陷阱。如果删除成功,此方法返回布尔值。
句法:
const p = new Proxy(target, {
deleteProperty: function(target, property) {
}
});
参数:此方法接受上面提到的两个参数,如下所述:
- Target:此参数保存目标对象。
- 属性:此参数保存要删除的属性的名称。
返回值:该方法返回一个布尔值,表示该属性是否被成功删除。
下面的示例说明了 JavaScript 中的 handler.deleteProperty() 方法:
示例 1:
javascript
const monster1 = {
Color: 'Green'
};
const handler1 = {
deleteProperty(target, prop) {
if (prop in target) {
delete target[prop];
console.log(`${prop} is property which is removed`);
}
}
};
console.log(monster1.Color);
const proxy1 = new Proxy(monster1, handler1);
delete proxy1.Color;
console.log(monster1.Color);
var f = { bar: 'baz' }
console.log('bar' in f)
delete f.bar
console.log('bar' in f)
javascript
const obj = new Proxy({}, {
deleteProperty: function(target, prop) {
if (prop in target){
delete target[prop]
console.log(prop+ ' property is removed.')
return true
}
else {
console.log(prop+ ' property is not removed.')
return false
}
}
})
let result
obj.prop1 = 10
console.log('prop1' in obj)
result = delete obj.prop1
console.log(result)
console.log('prop1' in obj)
result = delete obj.prop1
console.log(result)
输出:
"Green"
"Color is property which is removed"
undefined
true
false
示例 2:
javascript
const obj = new Proxy({}, {
deleteProperty: function(target, prop) {
if (prop in target){
delete target[prop]
console.log(prop+ ' property is removed.')
return true
}
else {
console.log(prop+ ' property is not removed.')
return false
}
}
})
let result
obj.prop1 = 10
console.log('prop1' in obj)
result = delete obj.prop1
console.log(result)
console.log('prop1' in obj)
result = delete obj.prop1
console.log(result)
输出:
true
"prop1 property is removed."
true
false
"prop1 property is not removed."
false
支持的浏览器: handler.deleteProperty() 方法支持的浏览器如下:
- 谷歌浏览器 49 及更高版本
- 边缘 12 及以上
- 火狐 18 及以上
- Opera 36 及以上
- Safari 10 及更高版本