js create classes and objects in several ways:
1, the most primitive manner:
var car = new Object(); car.color = "red"; car.name = "baoma"; car.showColor = function(){ alert(this.color); }
Create a car object has two properties: name, color a Method: showColor
Disadvantages: can only create an object
2, the factory method
function createCar() { var car= new Object; car.color = "blue"; car.name= "baoma"; car.showColor = function() { alert(this.color); }; return car; } var car1 = createCar(); var car2 = createCar();
The same way as the original, create car objects
Is superior than the original way: You can create multiple car object
Disadvantages: All object properties and methods are the same
3, the constructor method
function createCar(color,name) { this.color = color; this.name= name; car.showColor = function() { alert(this.color); }; } var car1 = createCar("blue","baoma"); var car2 = createCar("red","benci");
Disadvantages:
Generating function will repeat constructor for creating a separate version of each object
4, the prototype method:
function Car() { } Car.prototype.color = "blue"; Car.prototype.name = "baoma"; Car.prototype.showColor = function() { alert(this.color); };
Code:
First: define a constructor (Car), which without any code
Second: the use of structural properties and function prototype
When you call the new Car (), the prototype will be immediately given all the attributes of objects created, that are stored in an instance of Car is to point showColor () function pointer, semantic sense: all of the attributes that belong to a Object
The problems the prototype:
1, can not use the way of passing parameters to the property assignment
2, when the attribute points to an object rather than function, multiple instances of the object is rarely shared
5, mixed constructor / prototype approach
function Car(color,name) { this.color = color; this.name= name; }; } Car.prototype.showColor = function() { alert(this.color); };
Using this approach, the basic and other languages to create a kind of object.
This approach is most commonly used
This way: Even if all the functions only created once, and that each object has its own instance of the object properties
6, the prototype can be applied in this way the dynamic mode
function Car(color,name) { this.color = color; this.name = name; if (typeof Car._initialized == "undefined") { Car.prototype.showColor = function() { alert(this.color); }; Car._initialized = true; } }
The method uses the flag (_initialized) to determine whether any of the methods given to the prototype. The method to create and assign only one
The most common, best to use is the fifth, six, but the sixth perfect number