Home >Web Front-end >JS Tutorial >4 methods of javascript class definition_js object-oriented

4 methods of javascript class definition_js object-oriented

WBOY
WBOYOriginal
2016-05-16 18:46:49990browse
Copy code The code is as follows:

/*
Factory method --- Create and return specific types Factory function of the object
*/
function createCar(color,doors,mpg){
var tempCar = new Object;
tempCar.color = color;
tempCar. doors = doors;
tempCar.mpg = mpg;
tempCar.showCar = function(){
alert(this.color " " this.doors);
}
return tempCar;
}

/*
Constructor method --- The constructor looks a lot like a factory function
*/
function Car(color,doors,mpg){
this .color = color;
this.doors = doors;
this.mpg = mpg;
this.showCar = function(){
alert(this.color);
};
}
/*
Prototype method---Using the prototype attribute of the object, it can be regarded as the prototype on which new objects are created
*/
function Car(color,doors, mpg){
this.color = color;
this.doors = doors;
this.mpg = mpg;
this.drivers = new Array("nomad","angel");
}

Car.prototype.showCar3 = function(){
alert(this.color);
};

/*
Mixed constructor/ Prototype method --- Use constructors to define all non-function attributes of objects, and use prototype methods to define function attributes (methods) of objects
*/
function Car(sColor, iDoors, iMpg) {
this. color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike", "Sue");
}

Car.prototype.showColor = function () {
alert(this.color);
};
/*
Dynamic prototype method --- define non-function properties within the constructor, and Function properties are defined using prototype properties. The only difference is where the object methods are assigned.
*/
function Car(sColor, iDoors, iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this. drivers = new Array("Mike", "Sue");

if (typeof Car._initialized == "undefined") {

Car.prototype.showColor = function () {
alert(this.color);
};

Car._initialized = true;
}
} //This method uses the flag (_initialized) to determine whether the prototype has been assigned any method.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn