我正在使用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 );
};
为什么我们必须将Object传递给Descriptor
参数
我有两个代码片段,我在制作构造函数然后使用它创建对象。代码在控制台中返回相同的输出。使用.prototype.Methodname
改变了什么吗?
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() );
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);
答案 0 :(得分:0)
descriptor
参数是指正在定义或修改的属性,因此我们需要将其引用为键值对(键 =正在定义/修改的属性,值 =修改或赋予属性值)。因此descriptor
必须是Object
有关详细信息,请参阅MDN docs