JavaScript Inheritance Implementation

Source: Internet
Author: User

JavaScript Advanced Programming Reading notes

The book inherits several kinds of implementations, two of which are more reliable.

1 Combination Inheritance

//Parent ConstructorfunctionSuper (name) { This. Name =name;  This. colors = [' black ', ' red '];}
Super.prototype.getName=function() { return This. Name;

Child ConstructorsfunctionSub (name, age) {Super.call ( This, name); This. Age =Age ;}
By modifying the sub's prototype to a super instance, you can inherit the properties and methods in the Super.prototype,
The problem with this is that the name and colors attributes are also added to the Sub.prototype, which is not visible to the instance.
Because the call to new Sub () generates an instance, name and colors are added as instance properties Sub.prototype=NewSuper (); Sub.prototype.getAge=function(){ return This. Age;
When Sub.prototype is modified earlier, it causesSub.prototype.constructor point to Super, so change it back
=
var New Sub (' Mengxb ', 28);

2 Parasitic combined inheritance

functionObject (o) {functionF () {}; F.prototype=o; return NewF ();}functionInheritprototype (Sub, super) {varPrototype =Object (Super.prototype); Sub.prototype=prototype; Sub.prototype.construtor=Sub;}functionSuper (name) { This. Name =name;  This. colors = [' black ', ' red '];} Super.prototype.getName=function() {    return  This. Name;functionSub (name, age) {Super.call ( This, name);  This. Age =Age ;} Inheritprototype (Sub, Super); Sub.prototype.getAge=function(){    return  This. Age;

JavaScript Inheritance Implementation

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.