Analysis on inherited usage of constructors in js encapsulation, and js Constructor

Source: Internet
Author: User

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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.