Method 1: constructor.
- 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 ();
Copy code
Method 2: Factory method.
- 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 ();
Copy code
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.
- 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 ();
Copy code
However, the disadvantage of the original row chain is that all its attributes are shared, and all other attributes of an instance will be changed as long as one instance changes. For example:
- VaR coder1 = new coder ();
- VaR coder2 = new coder ();
- Alert (coder1.name);/* display "John "*/
- Coder2.name = 'old Wang ';
- Alert (coder1.name);/* shows "Old King "*/
- Alert (coder2.name);/* This also displays "Old King "*/
Copy code
Method 4: hybrid mode.
The above three methods all have their own shortcomings, so we need to improve them.
- Function coder (){
- This. Name = 'wang ';
- This. Job = 'programmer ';
- }
- Coder. Prototype. coding = function (){
- Alert ('Code I am writing ');
- };
Copy code
Method 5: Dynamic Source chain.
There is another way to solve the first three shortcomings.
- Function coder (){
- This. Name = 'wang ';
- This. Job = 'programmer ';
- If (typeof (CODER. _ init) = 'undefined '){
- This. coding = function ()
- {
- Alert ('Code I am writing ');
- };
- This. _ init = true;
- }
- }