Javascript Class

做个记录,javascript 如何创建类?

有早期的,有原型的,有构造函数的

// early javascript object
var o = {};
o.color = 'red';
o.showColor = function () {
    alert(this.color);
};
o.showColor();

// prototype
function Car() {}
Car.prototype.color = 'red';
Car.prototype.doors = 4;
Car.prototype.mpg = 23;
Car.prototype.drivers = new Array('Mike', 'Sue');
Car.prototype.showColor = function () {
    alert(this.color);
};
var oCar1 = new Car();
var oCar2 = new Car();
oCar1.drivers.push('Matt');
alert(oCar1.drivers); //outputs “Mike,Sue,Matt”
alert(oCar2.drivers); //outputs “Mike,Sue,Matt”

// prototype && constructor
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”

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

 

posted @ 2013-09-26 17:13  小言s  阅读(298)  评论(0编辑  收藏  举报