今日、私は 2 つの異なるタイプの Javascript 関数宣言を見ました。この 2 つをより深く理解したいと思います。
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());
具体的には「prototype」と「this.toString」です。
JS の知恵の真珠を教えてくれる人はいますか?