Hello!

There are 2 objects

var x={color:red} var y={foo:'bar',hoo:3} 

How through the prototype to copy all the properties of the object y to x. For new browsers, everything is OK through proto , and for proto through prototype I don’t see how.

    2 answers 2

     Object.prototype.extend = function( o ) { for( var i in o ) { if( o.hasOwnProperty(i) ) { this[i] = o[i]; } } } 

     var x={ color: 'red' }; var y={ foo : 'bar', hoo:3 }; x.extend( y ); console.log( x ); 
    • one
      Yes, there are 5 lines of code here (if you compress, in general, 3 =)) If you don’t know the for in loop, google and read, if you don’t know the hasOwnProperty method - likewise. The rest should be clear (actually there is nothing more there) Please - Zowie
    • 2
      @zloctb, if your problem is solved - do not forget to accept the answer. - Zowie
    • one
      @zloctb, and put the plus sign, as I just did. - Oleg
    • one
      @uWeb - this is optional =) - Zowie
    • one
      figured out! Errors corrected! - zloctb

    Try this method:

     Object.prototype.clone = function () { var instance = {}; for (i in this) { if (i == 'clone') continue; if (this[i] && typeof this[i] == "object") { instance[i] = this[i].clone(); } else instance[i] = this[i] } return instance; }; 
    • one
      Is this nonsense the right answer? O_O I ask because I really can't understand what the meaning of this code is ... - Zowie