javacript中构建对象的范式_Defining Classes and Objects in javacript

工厂范式 Factory paradigm

function showColor() {
alert(this.color);
}
function createCar(sColor, iDoors, iMpg) {
var oTempCar = new Object;
oTempCar.color = sColor;
oTempCar.doors = iDoors;
oTempCar.mpg = iMpg;
oTempCar.showColor = showColor;
return oTempCar;
}
var oCar1 = createCar(“red”, 4, 23);
var oCar2 = createCar(“blue”, 3, 25);
oCar1.showColor(); //outputs “red”
oCar2.showColor(); //outputs “blue”

缺点:工厂方法只能创建一种对象,且对象属性固定.

构造器范式 Constructor paradigm

function Car(sColor, iDoors, iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.showColor = function () {
alert(this.color)
};
}
var oCar1 = new Car(“red”, 4, 23);
var oCar2 = new Car(“blue”, 3, 25);

When a constructor is called with the new operator, an object is created before the first line of the constructor is executed; that object is accessible (at that point) only by using this. It is then possible to assign properties directly to this that are returned as the function value by default (no need to explicitly use the return operator).

这句讲了为啥使用new关键字能使得对象属性可用.并且和java的类构造器很像:

public class Car{
public Car(String sColor, String iDoors, String iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
}
}

原型范式 Prototype paradigm

function Car() {
}
Car.prototype.color = “red”;
Car.prototype.doors = 4;
Car.prototype.mpg = 23;
Car.prototype.showColor = function () {
alert(this.color);
};
var oCar1 = new Car();
var oCar2 = new Car();

这里是javascript最烂的地方,为了使创建的对象实例能够像java一样可以使用对象的属性,其使用了prototype而不是像java一样使用get和set方法.并且java中的prototype模式用于克隆对象.

混合构造器原型范式 Hybrid constructor/prototype paradigm

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);
};
var oCar1 = new Car(“red”, 4, 23);
var oCar2 = new Car(“blue”, 3, 25);
oCar1.drivers.push(“Matt”);
alert(oCar1.drivers); //outputs “Mike,Sue,Matt”
alert(oCar2.drivers); //outputs “Mike,Sue”

同样非常烂的一个设计,为了让属性赋值和方法声明分开.说明如下:
All the nonfunction properties are defined in the constructor, meaning that once again it is possible to assign default values by passing arguments into the constructor. Only one instance of the showColor() function is being created, so there is no wasted memory.

动态原型范式 Dynamic prototype method

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;
}
}

为了使showColor方法只初始化一次.

混合工厂模式 Hybrid factory paradigm

function Car() {
var oTempCar = new Object;
oTempCar.color = “red”;
oTempCar.doors = 4;
oTempCar.mpg = 23;
oTempCar.showColor = function () {
alert(this.color)
};
return oTempCar;
}

var car = new Car();