当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Javascript handler.deleteProperty()用法及代码示例


JavaScript中的handler.deleteProperty()方法是delete运算符的陷阱。如果删除成功,则此方法返回布尔值。

用法:

const p = new Proxy(target, {
  deleteProperty:function(target, property) {
  }
});

参数:该方法接受上述和以下所述的两个参数:



  • Target:此参数保存目标对象。
  • Property:此参数保存要删除的属性的名称。

返回值:此方法返回一个布尔值,该值指示该属性是否已成功删除。

以下示例说明了JavaScript中的handler.deleteProperty()方法:

范例1:

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) 

输出:

"Green"
"Color is property which is removed"
undefined
true
false

示例2:

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()方法支持的浏览器如下:

  • 谷歌浏览器
  • Firefox
  • Opera
  • Safari
  • Edge



相关用法


注:本文由纯净天空筛选整理自SHUBHAMSINGH10大神的英文原创作品 JavaScript | handler.deleteProperty() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。