Analysis on inherited usage of constructors in js encapsulation, and js Constructor
The example in this article describes the inheritance usage of constructors that can be used in js encapsulation. Share it with you for your reference. The details are as follows:
Let's take a look at the following code.
(YUI) library method:
Copy codeThe Code is 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, property copy:
This method is different from the previous one. Because the child prototype has been extended, you do not need to reset the child. prototype. constructor attribute because it will not be overwritten.
Compared with the previous method, this method is much more efficient. This is because the sub-object prototype is copied one by one. Instead of simply querying the prototype chain.
This method only applies to objects that only contain basic data types. All object types, including functions and arrays, cannot be copied. They only support reference transmission.
Copy codeThe Code is 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 help you design javascript programs.