One of the JavaScript class inheritance implementations

Source: Internet
Author: User

Online blog Forum appeared a lot of JavaScript class inheritance methods, browse some, not without comments, is not running effect, so I wrote a simple and understandable version, with the test code at the bottom.

The article has just been accidentally deleted, so it is re-made, and the example is strengthened.

(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 the 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 A");
}
};

var B = function () {};

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

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

B.extend (A);

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 ();

One of the JavaScript class inheritance implementations

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.