The Object.create () method creates a new object using the specified prototype object and its properties. Grammar
Object.create (proto[, Propertiesobject])
ParametersProto the prototype object for the newly created object. Propertiesobject Optional. If not specified as undefined, the property descriptor of the object to add to the newly created object (that is, its own defined property, not the enumeration property on its prototype chain), and the corresponding property name. These properties correspond to the second parameter of Object.defineproperties ().
return value
The object after the new attribute is added to the specified prototype object. Exceptions
If the proto parameter is not null or an object, a TypeError exception is thrown. Example implementation of class inheritance with Object.create
The following example shows how to use Object.create () to implement class inheritance. This is a single inheritance supported by all versions of JavaScript.
//Shape-Parent class (superclass) function Shape () {this.x = 0;
This.y = 0;
}//Parent class Method Shape.prototype.move = function (x, y) {this.x = x;
This.y = y;
Console.info (' Shape moved. ');
};
Rectangle-Subclass (Subclass) function Rectangle () {shape.call (this);//Call Super constructor.}
Subclass Continuation Parent Class Rectangle.prototype = Object.create (Shape.prototype);
Rectangle.prototype.constructor = Rectangle; Because of the use of ". Prototype = ...", constructor will change to the one//constructor of "= ...", so to reassign. Constructor for itself.
var rect = new Rectangle ();
Console.log (' is rect a instance of Rectangle? ',
rect instanceof-Rectangle);//True
Console.log (' is rect a Insta nCE of shape? ',
rect instanceof shape); True
rect.move (1, 1);//outputs, ' Shape moved. '
If you want to be able to inherit multiple objects, you can use the mixed method.
function MyClass () {
superclass.call (this);
Othersuperclass.call (this);
}
Inheriting a class
Myclass.prototype = Object.create (superclass.prototype);
Mixed
with other object.assign (Myclass.prototype, othersuperclass.prototype);
Re-designate constructor
MyClass.prototype.constructor = MyClass;
MyClass.prototype.myMethod = function () {
//do a thing
};
/p>