我看一下 Addy Osmani 关于构造函数模式的章节:http: //addyosmani.com/resources/essentialjsdesignpatterns/book/#constructorpatternjavascript 我遇到了以下内容:
function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
this.toString = function () {
return this.model + " has done " + this.miles + " miles";
};
}
// Usage:
// We can create new instances of the car
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
// and then open our browser console to view the
// output of the toString() method being called on
// these objects
console.log( civic.toString() );
console.log( mondeo.toString() );
他说这对于 this.toString 函数来说并不是一件好事,因为它不是非常理想的并且不是在汽车类型的所有实例之间共享。但他没有解释这究竟意味着什么以及为什么这是一件坏事。他建议执行以下操作:
function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
}
// Note here that we are using Object.prototype.newMethod rather than
// Object.prototype so as to avoid redefining the prototype object
Car.prototype.toString = function () {
return this.model + " has done " + this.miles + " miles";
};
// Usage:
var civic = new Car( "Honda Civic", 2009, 20000 );
var mondeo = new Car( "Ford Mondeo", 2010, 5000 );
console.log( civic.toString() );
console.log( mondeo.toString() );
有人可以解释为什么使用原型对象添加此功能是最佳/更好的吗?