function clone(proto, properties){ properties.__proto__ = proto; return properties; }
In prototype-based systems, two methods are provided for creating a new object: cloning an existing object, or creating an object from scratch. To create an object from scratch, programmers are provided with syntactic means of adding properties and methods to an object. Further, a complete copy can be obtained from the resulting object - a clone. In the process of cloning a copy inherits all the characteristics of its prototype, but from that moment it becomes independent and can be changed.© Wikipedia
clone()
function, as the name suggests, creates clones of objects. A clone is a lazy shallow copy , that is, it is not actually a copy, but simply a reference to an object, but if you add / replace any of its properties, it will not affect the parent object (prototype).Object.create(null)
). /// "" var duck$ = { name: "Unnamed", quack: function(){ console.log( this.name +" Duck: Quack-quack!"); } }; /// var talkingDuck$ = clone( duck$, { quack: function(){ duck$.quack.call(this); console.log("My name is "+ this.name +"!"); } }); /// var donald = clone( talkingDuck$, {name: "Donald"});
/// object$ – var object$ = { clone: function(properties){ properties.__proto__ = this; return properties; }; /// "" var duck$ = object$.clone({ name: "Unnamed", quack: function(){ console.log( this.name +" Duck: Quack-quack!"); } }; /// var talkingDuck$ = duck$.clone({ quack: function(){ duck$.quack.call(this); console.log("My name is "+ this.name +"!"); } }); /// var donald = talkingDuck$.clone({name: "Donald"});
function clone(proto, properties){ var newObj = {__proto__: proto}; for(var key in properties) newObj[key] = properties[key]; return newObj; }
The use of the second argument after cloning is undesirable, and is possible using only its own properties.This rule will also ensure compatibility with Internet Explorer 6–10 and ECMA Script 3:
function clone(/** Object */proto, /** ObjLiteral= */ownProperties){ function Clone(ownProperties){ for(var key in ownProperties) this[key] = ownProperties[key]; }; Clone.prototype = proto; return new Clone(ownProperties); }
Source: https://habr.com/ru/post/192806/
All Articles