javascript设计模式之构造函数模式

// 构造函数模式
function Car(name, logo) {
    // 强制使用new, "this" point to the instance
    if (!(this instanceof Car)) {
        return new Car(name, logo);
    }

    this.name = name;
    this.logo = logo;
}

// Car.prototype is the original object, that every instance pointed to.
Car.prototype.output = function () {
    return (this.name + " : " + this.logo);
}

// new Car("King", "horse");
var mycar = Car("King", "horse");  // this is equal "new Car('King', 'horse')"

console.log(mycar.output());  // King : horse


console.log(Car.prototype === mycar.__proto__);  // true
console.log(Car.prototype.constructor === Car);  // true

 

posted @ 2014-09-10 14:33  farawayfromhome  阅读(194)  评论(0编辑  收藏  举报