使用动态原型方法定义Car类
另外使用对象的prototype属性可以为已知类添加新的方法。
例如
关于Array的indexOf也可以这么写
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属性可以为已知类添加新的方法。
例如
Array.prototype.enqueue = function(vItem) {
this.push(vItem);
};
Array.prototype.dequeue = function() {
return this.shift();
};
Array.prototype.indexOf = function (vItem) {
for (var i=0; i<this.length; i++) {
if (vItem == this[i]) {
return i;
}
}
return -1;
}
关于Array的indexOf也可以这么写
Array.indexOf = (Array.prototype.indexOf) ?
function(a, val) {
return Array.prototype.indexOf.call(a, val);
} :
function(a, val) {
for (var i=0; i<a.length; i=i+1) {
if (a[i] === val) {
return i;
}
}
return -1; //寻找不到的情况
};