Although javascript does not support inheritance directly by using keywords or symbols, we can also implement inheritance in some bad ways. Method 1: functionBase (word) {this. sayfunction () {returnword;} this. wordword;} f... SyntaxHighlight
Although javascript does not support inheritance directly by using keywords or symbols, we can also implement inheritance in some bad ways.
Method 1:
Function Base (word ){
This. say = function (){
Return word;
}
This. word = word;
}
Function Sub (word ){
This. hello = function (){
Return 'hello' + word;
}
}
Sub. prototype = new Base ();
Sub. prototype. constructor = Sub;
This method is the most common inheritance method, but we will note that the Base class Base constructor requires a word parameter, when Sub-classes inherit the Base class, they cannot pass their own word parameters to the Base class.
The value obtained by new Sub (). say () is always undefined.
Method 2:
Function Base (word ){
This. say = function (){
Return word;
}
This. word = word;
}
Function Sub (word ){
Var base = new Base (word );
Base. hello = function () {return 'hello' + word ;}
Reurn base;
}
Var sub = Sub (word );
This method seems much simpler than the first method, and solves the problem of passing parameters.
But this method subclass is var sub = Sub (word); unlike the first method var sub = new Sub (word );
For people with obsessive-compulsive disorder with the new Keyword, does it seem very tangled? Does this statement always think that Sub is not like a class.
Method 3:
Function Base (word ){
This. say = function (){
Return word;
}
This. word = word;
}
Function Sub (word ){
$. Extend (this, (new Base ). constructor. apply (this, arguments); // call the constructor of the Base to copy the attributes and methods of the initialized instance to this.
This. hello = function (){
Return word;
}
}
Sub. prototype = Base. prototype; // ensure that new Sub () instanceof Base = true
Sub. prototype. constructor = Sub; // set contructor to itself
This method solves the problem that the first method cannot pass parameters for the base class constructor, and makes the class instantiation method look more natural.
But I have checked a lot of information, but I have never read www.2cto.com.
Sub. prototype = Base. prototype;
I don't know if there are any hidden risks.
From flowforever