今天看到了两种不同类型的 Javascript 函数声明,我想对这两者有更深入的了解:
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";
};
var civic = new Car( "Honda Civic", 2009, 20000);
var mondeo = new Car( "Ford Mondeo", 2010, 5000);
console.log(civic.toString());
和类型 2:
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";
};
}
var civic = new Car( "Honda Civic", 2009, 20000);
var mondeo = new Car( "Ford Mondeo", 2010, 5000);
console.log(civic.toString());
特别是“原型”和“this.toString”。
任何人都可以传授一些 JS 智慧的珍珠吗?