This article describes the constructor inheritance usage that can be used by js encapsulation. Share it for your reference. The details are as follows:
Let's take a look at the following code
Methods used in the (YUI) library:
Copy the code as follows: function extend(Child, Parent) {
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 before. Since the child prototype has been extended, there is no need to reset the child.prototype.constructor property because it will not be overwritten again.
Compared with the previous method, this method is obviously better in efficiency. Because what is executed here is a copy of the sub-object prototype one by one. Rather than a simple prototype chain query.
This method is only applicable to objects that only contain basic data types. All object types, including functions and arrays, are not replicable. They only support reference passing.
Copy the code as follows: function extend2(Child, Parent) {
var p = Parent.prototype;
var c = Child.prototype;
for (var i in p) {
c[i] = p[i];
}
c.uber = p;
}
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.