首页 > 代码库 > javascript设计模式之构造函数模式

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 : horseconsole.log(Car.prototype === mycar.__proto__);  // trueconsole.log(Car.prototype.constructor === Car);  // true

 

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