JavaScript does not give an inherited keyword, but we can still come up with some good ways to achieve it.
1, prototype chain inheritance:
Copy Code code as follows:
var Base = function ()
{
This.level = 1;
THIS.name = "base";
this.tostring = function () {
return "base";
};
};
Base.constant = "CONSTANT";
var Sub = function ()
{
};
Sub.prototype = new Base ();
Sub.prototype.name = "Sub";
Advantages: From the instanceof keyword, an instance is both an instance of the parent class and an instance of a subclass, which seems to be the purest inheritance.
Disadvantage: Subclasses differ from the parent class's properties and methods and must be Sub.prototype = new Base (), which are executed separately and cannot be wrapped into the sub's constructor. For example: Sub.prototype.name = "Sub"; multiple inheritance cannot be implemented.
2. Construct Inheritance:
Copy Code code as follows:
var Base = function ()
{
This.level = 1;
THIS.name = "base";
this.tostring = function () {
return "base";
};
};
Base.constant = "CONSTANT";
var Sub = function ()
{
Base.call (this);
THIS.name = "Sub";
};
Advantages: Multiple inheritance can be implemented, and can be placed inside the constructor with the property settings peculiar to the handle.
Disadvantage: Using instanceof to discover that an object is not an instance of a parent class.
3. Instance Inheritance:
Copy Code code as follows:
var Base = function ()
{
This.level = 1;
THIS.name = "base";
this.tostring = function () {
return "base";
};
};
Base.constant = "CONSTANT";
var Sub = function ()
{
var instance = new Base ();
Instance.name = "Sub";
return instance;
};
Benefits: Is the object of the parent class, and you can get the same effect by using new to construct the object and not using new to construct the object.
Disadvantage: The generated object is simply an instance of the parent class, not an object of a subclass, and does not support multiple inheritance.
4. Copy Inheritance:
Copy Code code as follows:
var Base = function ()
{
This.level = 1;
THIS.name = "base";
this.tostring = function () {
return "base";
};
};
Base.constant = "CONSTANT";
var Sub = function ()
{
var base = new Base ();
for (var i in base)
Sub.prototype[i] = Base[i];
sub.prototype["Name" = "Sub";
};
Benefits: Supports multiple inheritance.
Disadvantage: low efficiency; Cannot get methods that the parent class cannot enumerate.
Each of these forms has its own characteristics and, in the case of the code I provide, satisfies the following table:
2012-1-10: Add, if we do not need class inheritance, only object inheritance, for browsers that support ECMAScript 5, can also be implemented using the Object.create method:
Copy Code code as follows:
var Base = function ()
{
This.level = 1;
THIS.name = "base";
this.tostring = function () {
return "base";
};
};
Base.constant = "CONSTANT";
var sub = object.create (New Base ());
Sub.name = "Sub";