Anyone who has studied Java, C#, and VB knows the concept of classes, and classes have functions such as inheritance, encapsulation, and polymorphism. JavaScript is not an object-oriented language, it is an interpreted language.
But we can also use JavaScript to implement inheritance and polymorphism.
Javascript implementation class has many methods.
Method 1: Construction method.
Code
function coder(){
this.name = 'Xiao Wang';
this.job = 'Programmer';
this.coding = function ()
{
alert('I am writing code');
}
}
var coder=new coder();
alert(coder.name);
coder.coding();
Method 2: Factory method .
Code
function createCoderFactory(){
var obj=new Object();
obj.name = 'Xiao Wang';
obj.job = 'Programmer';
obj.coding = function (){
alert('I Writing code');
};
return obj;
}
var coder = createCoderFactory();
alert(coder.name);
coder.coding();
But the factory method and the constructor method both have the same shortcoming, that is, every time an instance is created, every function of the class will be instantiated.
Method 3: Prototype chain.
Code
function coder(){}
coder.prototype.name = 'Xiao Wang';
coder.prototype.job = 'Programmer';
coder.prototype.coding = function(){
alert('I am writing code' );
};
var coder = new coder();
alert(coder.name);
coder.coding();
Note: in the book Said: A disadvantage of the prototype chain is that all its attributes are shared. As long as one instance changes, the others will change accordingly. The test is as follows:
var coder1 = new coder();
var coder2 = new coder();
alert(coder1.name); /*Display "Xiao Wang"*/
coder2.name = 'Old Wang';
alert(coder1.name) ; /*This displays "Xiao Wang". According to the book, it should display "Lao Wang"*/
alert(coder2.name); /*This displays "Lao Wang"*/
alert(coder1 .name); According to the book, it should display "Lao Wang", but here it displays "Xiao Wang", so the book is wrong.
Method 4: Mixing method.
The above three types all have their own shortcomings, so we need to improve them.
function coder(){
this.name = 'Xiao Wang';
this.job = 'Programmer';
}
coder.prototype.coding = function(){
alert('I am writing code');
};
Method 5: Dynamic original chain.
There is another way to solve the first three shortcomings.
Code
function coder(){
this.name = 'Xiao Wang';
this.job = 'Programmer';
if (typeof(coder._init) == 'undefined'){
this.coding = function ()
{
alert('I'm writing code');
};
this._init = true;
}
}
What about this method? , when used for the first time, since _init is not initialized, the following code will be executed to instantiate the coding function. It will not be executed again in the future, so the function is only instantiated once.