一、JavaScript 创建对象

javascript 创建对象
    采用常用混合的构造函数/原型方式
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); //输出 "Mike,Sue,Matt"
alert(oCar2.drivers); //输出 "Mike,Matt"

    引出一种类似与面向对象的设计模式
Car = function(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); //输出 "Mike,Sue,Matt"
alert(oCar2.drivers); //输出 "Mike,Matt"


附:
dtree 便是学习javascript创建对象的很好的例子。(混合的构造函数/原型方式)

你可能感兴趣的:(JavaScript,设计模式,prototype)