递归地检查原型上的属性,如果存在则从原型中删除

Recursively check for property on prototype and delete it from prototype if it exists

本文关键字:原型 存在 如果 删除 属性 检查 递归      更新时间:2023-09-26

我正试图编写代码来删除对象中的属性。如果它是继承的,它必须沿着链向上并从祖先中删除它。到目前为止,我已经想出了这个(不工作):

// My objects:
   var pro = {'a':1};
    var pro2 = Object.create(pro);
    var pro3 = Object.create(pro2);

// -----------------------------------------------------

    function deleteProp(obj, prop){
        console.log(obj,prop)
        //get own properties
        var ownprop = Object.getOwnPropertyNames(obj);

        for(var i=0 ;i <ownprop.length; i++){
            if (prop === ownprop[i]){
                delete obj.ownprop[i];
            }
            else{ 
           //get the parent
                var parent = Object.getPrototypeOf(obj);
                console.log(parent);
                while (Object.getPrototypeOf(parent)!== Object.prototype){
             //recursive call
                    deleteProp(parent, prop);
                }
            }
        }
    }

这里并不需要递归——一个简单的while循环就足够了。

function deleteProp(obj, prop) {
  while (obj && obj !== Object.prototype) {
    delete obj[prop];
    obj = Object.getPrototypeOf(obj);
  }
}

检查obj是必要的,因为对象可能没有原型,例如,如果它是用Object.create(null)创建的。

从输出来看,这应该是您想要的。

var pro = {'a':1};
var pro2 = Object.create(pro);
var pro3 = Object.create(pro2);
function deleteProp(obj, prop) {
  do {
    delete obj[prop];
  }
  while ((obj = Object.getPrototypeOf(obj)));
}
console.log('before', pro.a, pro2.a, pro3.a);
deleteProp(pro3, 'a');
console.log('after', pro.a, pro2.a, pro3.a);

Edit:这能行吗?