1

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

1 回答 1

0

参数是指正在定义或修改的descriptor属性,因此我们需要将其称为键值对(key = 正在定义/修改的属性,value = 修改或分配给属性的值)。因此descriptor必须是一个Object

有关详细信息,请参阅MDN 文档

于 2017-09-19T09:36:21.193 回答