One of the implementation of JavaScript class inheritance

Source: Internet
Author: User

One of the implementation of JavaScript class inheritance

Many JavaScript class inheritance methods have emerged in various blog forums on the Internet. I have browsed some of them, either without comments or without running effects, so I wrote a concise and easy-to-understand version, the accompanying test code is at the bottom.

I accidentally deleted this article, so I made it up again and added an example.

(Function (){

Function. prototype. extend = function (baseClass ){

// This is a function object.
Var oldPrototype = this. prototype, newPrototype = {}, _ super = new baseClass ();

// Inherits all properties and methods.
For (var name in _ super ){
NewPrototype [name] = _ super [name];
}

For (var name in oldPrototype ){
// Only override properties in this new Class.
If (oldPrototype. hasOwnProperty (name )){
// Only function need _ super.
If (typeof oldPrototype [name] = "function" & typeof _ super [name] = "function "){
NewPrototype [name] = (function (name, fn ){
Return function (){
Var tmp = this. _ super;

// Set super method
This. _ super = _ super [name];

Var ret = fn. apply (this, arguments );

This. _ super = tmp;

Return ret;
};
}) (Name, oldPrototype [name]);
}
}
}

This. prototype = newPrototype;

Return this;
};
})();

Var A = function (){
This. hello = function (){
Console. log ("hello, I'm ");
}
};

Var B = function (){};

B. prototype = {
Hello: function (){
This. _ super ();

Console. log ("hello, I'm B ");
}
};

B. extend ();

Var C = function (){};

C. prototype = {
Hello: function (){
This. _ super ();

Console. log ("hello, I'm C ");
}
};

C. extend (B );

Var B = new B ();
Var c = new C ();

// B. hello ();
C. hello ();

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.