Although JavaScript does not provide inherited keywords, we can still come up with some good ways to implement them.
1. Prototype chain inheritance:
The code copy is 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: Judging from the instanceof keyword, an instance is both an instance of the parent class and an instance of the child class, which seems to be the purest inheritance.
Disadvantages: Subclasses are different from the properties and methods of the parent class. They must be executed separately after statements such as Sub.prototype = new Base(); and cannot be wrapped into the Sub constructor. For example: Sub.prototype.name = "sub"; multiple inheritance cannot be achieved.
2. Construct inheritance:
The code copy is 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 attributes unique to subclasses can be set inside the constructor.
Disadvantages: Using instanceof found that the object is not an instance of the parent class.
3. Instance inheritance:
The code copy is 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;
};
Advantages: It is an object of the parent class, and the same effect can be obtained by using new to construct objects and without using new to construct objects.
Disadvantages: The generated object is essentially an instance of the parent class, not a subclass object; multiple inheritance is not supported.
4. Copy inheritance:
The code copy is 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";
};
Advantages: Supports multiple inheritance.
Disadvantages: Low efficiency; unable to obtain methods that cannot be enumerated by the parent class.
These forms have their own characteristics, and only in terms of the code I provide, they satisfy the following table:
2012-1-10: Added, if we do not need class inheritance, we only need object inheritance. For browsers that support ECMAScript 5, we can also use the Object.create method to implement it:
The code copy is 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";