Home >Web Front-end >JS Tutorial >Analysis of constructor inheritance usage that can be used in js package_javascript skills
The examples in this article describe the use of constructor inheritance that can be used in js encapsulation. Share it with everyone for your reference. The details are as follows:
Let’s take a look at the following code first
Methods used by the (YUI) library:
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}
There is also a copy inheritance method, attribute copy:
This method is different from the previous one. Since the extension of child's prototype has been completed, there is no need to reset the child.prototype.constructor property because it will no longer be overwritten.
Compared with the previous method, this method is obviously slightly less efficient. Because what is performed here is to copy the prototypes of the sub-objects one by one. Rather than a simple prototype chain query.
This method is only applicable to objects containing only basic data types. All object types, including functions and arrays, are not copyable and they only support reference passing.
var Shape = function(){}
var TwoDShape = function(){}
Shape.prototype.name = 'shape';
Shape.prototype.toString = function(){
return this.name;
}
extend2(TwoDShape,Shape);
var t = new TwoDShape();
t.name
//-->"shape"
t.toString();
//-->"shape"
TwoDShape.prototype.name = 'TwoDShape';
t.name
//-->"2d shape"
t.toString();
//-->"2d shape"
TwoDShape.prototype.toString === Shape.prototype.toString
//-->true
TwoDShape.prototype.name === Shape.prototype.name
//-->false
I hope this article will be helpful to everyone’s JavaScript programming design.