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


i trying write code delete property in object. if inherited, must go chain , delete itfrom ancestor. far have come (doesnot work):

// 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 parent                 var parent = object.getprototypeof(obj);                 console.log(parent);                 while (object.getprototypeof(parent)!== object.prototype){               //recursive call                     deleteprop(parent, prop);                 }             }         }     } 

you don't need recursion here--a simple while loop suffice.

function deleteprop(obj, prop) {   while (obj && obj !== object.prototype) {     delete obj[prop];     obj = object.getprototypeof(obj);   } } 

the check obj necessary because object may have no prototype, instance if created object.create(null).


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -