defineProperty
オブジェクトのプロパティを作成するために使用しています。descriptor
関数内のパラメータは必ずobject
. コードは次のとおりです。
var config=new Object();
var defineProp = function ( obj, key, value ){
config.value = value; // why should this parameter be an object?
Object.defineProperty( obj, key, config );
};
Descriptor
オブジェクトをパラメーターに渡す必要があるのはなぜですか
以下の 2 つのコードは、コンストラクターを作成し、それを使用してオブジェクトを作成しています。どちらのコードも、コンソールに同じ出力を返します。使って.prototype.Methodname
何か変わる?
1
function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
}
Car.prototype.toString = function () {
return this.model + " has done " + this.miles + " miles";
};
// Usage:
var civic = new Car( "Honda Civic", 2017, 30000 );
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", 2017, 30000 );
console.log( civic.toString() );
コードの使用法は次のとおりです。
var civicSport= Object.create( person );
defineProp(civicSport, "topSpeed", "120mph");//function created above
console.log(civicSport);