Some time ago, after learning "ajax self-taught manual", I realized that javascript can still be written like this. I have learned the concepts of classes in java, c #, and vb, and classes have functions such as inheritance, encapsulation, and polymorphism. Javascript is not an object-oriented language, but an explanatory language.
But we can also use javascript to implement inheritance and polymorphism.
Javascript implementation class, there are multiple methods.
Method 1: constructor.
Code
The Code is as follows:
Function coder (){
This. name = 'wang ';
This. job = 'programmer ';
This. coding = function ()
{
Alert ('Code I am writing ');
}
}
Var coder = new coder ();
Alert (coder. name );
Coder. coding ();
Method 2: Factory method.
Code
The Code is as follows:
Function createCoderFactory (){
Var obj = new Object ();
Obj. name = 'wang ';
Obj. job = 'programmer ';
Obj. coding = function (){
Alert ('Code I am writing ');
};
Return obj;
}
Var coder = createCoderFactory ();
Alert (coder. name );
Coder. coding ();
However, both the factory method and constructor method share the same disadvantage, that is, every function of this class is instantiated every time an instance is created.
Method 3: prototype chain.
Code
The Code is as follows:
Function coder (){}
Coder. prototype. name = 'John ';
Coder. prototype. job = 'programmer ';
Coder. prototype. coding = function (){
Alert ('Code I am writing ');
};
Var coder = new coder ();
Alert (coder. name );
Coder. coding ();
Note: The book says: the disadvantage of prototype chain is that all its attributes are shared, and all other attributes of a prototype chain will change as long as one instance changes. The test is as follows:
The Code is as follows:
Var coder1 = new coder ();
Var coder2 = new coder ();
Alert (coder1.name);/* display "John "*/
Coder2.name = 'old Wang ';
Alert (coder1.name);/* This shows "Mr. Wang". If it is shown in the book, it should be "Old Wang "*/
Alert (coder2.name);/* This shows "Old King "*/
Alert (coder1.name); if "Old Wang" is displayed in the book, but "Little Wang" is displayed here, an error occurs in the book.
Method 4: hybrid mode.
The above three methods all have their own shortcomings, so we need to improve them.
The Code is as follows:
Function coder (){
This. name = 'wang ';
This. job = 'programmer ';
}
Coder. prototype. coding = function (){
Alert ('Code I am writing ');
};
Method 5: Dynamic Source chain.
There is another way to solve the first three shortcomings.
Code
The Code is as follows:
Function coder (){
This. name = 'wang ';
This. job = 'programmer ';
If (typeof (coder. _ init) = 'undefined '){
This. coding = function ()
{
Alert ('Code I am writing ');
};
This. _ init = true;
}
}
This method, when used for the first time, because _ init is not initialized, the following code will be executed to instantiate the coding function. It will not be executed in the future, so that the function will be instantiated only once.