Ben*_*enM 5 javascript constructor
我看看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() );
Run Code Online (Sandbox Code Playgroud)
他说这对于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() );
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么使用原型对象添加此功能是最佳/更好的?
所有实例共享原型对象上的函数(更一般地说,属性).无论制作了多少"Car"实例,单个"toString"函数仍然只是一个单独的对象.在构造函数中执行赋值时,会为每个赋值创建一个新的函数对象.
显然,如果每个实例都需要一个可能与其他实例不同的属性,那么您需要一个per-instance属性.