defineProperty描述符参数和Object.prototype困境

时间:2017-09-19 07:06:23

标签: javascript design-patterns prototype ecmascript-5 defineproperty

我正在使用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改变了什么吗?

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);

1 个答案:

答案 0 :(得分:0)

descriptor参数是指正在定义或修改的属性,因此我们需要将其引用为键值对( =正在定义/修改的属性, =修改或赋予属性值)。因此descriptor必须是Object

有关详细信息,请参阅MDN docs