欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

笔记

程序员文章站 2022-07-12 21:09:21
...
目前使用最广泛的是混合的构造函数/原型方式。此外,动态原始方法也很流行,在功能上与构造函数/原型方式等价。
[size=medium]混合的构造函数/原型方式[/size]
function Car(sColor,iDoors,iMpg) {  
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike","John");
}

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

var oCar1 = new Car("red",4,23);
var oCar2 = new Car("blue",3,25);

oCar1.drivers.push("Bill");

alert(oCar1.drivers); //输出 "Mike,John,Bill"
alert(oCar2.drivers); //输出 "Mike,John"

[size=medium]动态原型方法[/size]
    function Car(sColor,iDoors,iMpg) {  
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike","John");

if (typeof Car._initialized == "undefined") {
Car.prototype.showColor = function() {
alert(this.color);
};

Car._initialized = true;
}
}
相关标签: prototype