javascript - Iterating through object's properties lists things in the prototype -


i'm trying make "copy" function , add object's prototype. planned recursively typecheck , assign properties new object , return object... but, there seems problem, see snippet of code:

object.prototype.copy = function() {     (prop in this)     {         console.log(prop); //logs copy (the function)!!!     } }  x = {"a": 1}; y = x.copy(); 

as i've pointed out in comment, found weird behavior, why happening? copy function should in object.prototype, not in instanced object itself! how fix it? can set this.copy = undefined, , still rely on object.prototype.copy?

this full code sample, requested:

object.prototype.copy = function() {     var object = this; //the object copying.     var newobject = {}; //the object return.      //cycle through properties of object creating, copy them recursively.     (prop in object)     {         if (!object.prototype.hasownproperty.call(this, prop) || object[prop] == null)         {             continue;         }          if (prop == "copy")         {             console.log("well, blah."); //this never prints!         }          if (typeof(object[prop]) == "object" && !(object[prop] instanceof array)) //if object's property object...         {             newobject[prop] = object[prop].copy(); //set copy of new object well.             console.log("1 --- " + prop); //this prints copy - 2 times! defies logic!         }         else if (typeof(object[prop]) == "object") //if it's array...         {             newobject[prop] = object[prop].slice(); //do in nicer fashion.             console.log("2 --- " + prop);         }         else //you're safe copy it.         {             newobject[prop] = object[prop];             console.log("3 --- " + prop + " --- " + object[prop]);         }     }      return newobject; } 

there's method called "hasownproperty" can use:

 if (this.hasownproperty(prop)) { ... } 

if function returns true it's "direct" property on object.

if fear "hasownproperty" method may borked, can this:

if (object.prototype.hasownproperty.call(this, prop)) { ... } 

instead.

newer versions of javascript have fancier ways of examining , controlling objects.

edit — updated code involves problem that'll bite due nested calls "copy": didn't declare "prop" var, after call copy object, value of "prop" have changed! (every call "copy" shares same variable, in other words.)


Comments

Popular posts from this blog

All overlapping substrings matching a java regex -

c++ - Using OpenSSL in a multi-threaded application -

php - Deleting/Renaming a locked file -