js创建类的方法

125 阅读1分钟
//工厂方式
function Car() {
    var ocar = new Object;
    ocar.color = 'blue'
    ocar.doors = 4;
    ocar.showColor = function () {
        document.write(this.color)
    };
    return ocar;
}
var car1 = Car();
var car2 = Car();
//构造方式
function Car(color, door) {
    this.color = color;
    this.doors = door;
    this.showColor = function () {
        alert(this.color)
    };
}
var car1 = new Car('red', 4);
var car2 = new Car('blue', 4);

//原型方式
function Car() {}
Car.prototype.color = 'red';
Car.prototype.doors = 4;
Car.prototype.showColor = function () {
    alert(this.color);
}
var car1 = new Car();
var car2 = new Car();
//原型原型方式
function Car(color, door) {
    this.color = color;
    this.doors = door;
    this.arr = new Array('aa', 'bb');
    if (typeof Car._initialized == undefined) {
        Car.prototype.showColor = function () {
            alert(this.color);
        };
        Car._initialized = true;
    }
}