Javascript itself does not support object-oriented features. It does not have an access control operator and does not define the class keyword. It does not support inherited extend or colons, nor does it support virtual functions, however, Javascript is a flexible language. Let's take a look at how Javascript without a keyword class implements class definition and creates objects. When it comes to object-oriented, we can think of classes, objects, encapsulation, inheritance, and polymorphism. The description in the book javaScript advanced programming is quite detailed. Let's take a look at various methods of defining classes in JavaScript.
Constructor
Function coder () {this. name = 'modern magine'; this. job = 'web developer'; this. coding = function () {alert ('I am writing Code') ;}} var coder = new coder (); alert (coder. name); coder. coding ();
Factory method
Function createCoderFactory () {var obj = new Object (); obj. name = 'modern magic '; obj. job = 'programmer '; obj. coding = function () {alert ('Code I am writing ') ;}; return obj ;}var coder = createCoderFactory (); alert (coder. name); coder. coding ();
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.
Prototype chain
Function coder () {} coder. prototype. name = 'modern magic '; coder. prototype. job = 'programmer '; coder. prototype. coding = function () {alert ('I am writing Code') ;}; var coder = new coder (); alert (coder. name); coder. coding ();
The disadvantage of a prototype 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 modern magic */coder2.name = 'bkja'; alert (coder1.name ); /* display bkjia */alert (coder2.name);/* This also shows bkjia */
Hybrid mode
The above three methods all have their own shortcomings, so we need to improve them.
Function coder () {this. name = 'modern magine'; this. job = 'programmer ';} coder. prototype. coding = function () {alert ('Code I am writing ');};
Dynamic original chain
There is another way to solve the first three shortcomings.
Function coder () {this. name = 'modern magine'; this. job = 'programmer '; if (typeof (coder. _ init) = 'undefined') {this. coding = function () {alert ('Code I am writing ') ;}; this. _ init = true ;}}