【发布时间】:2017-09-19 07:06:22
【问题描述】:
我正在使用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参数传递一个Object
我有以下两个代码片段,我在其中创建一个构造函数,然后使用它创建对象。这两个代码在控制台中返回相同的输出。使用.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);
【问题讨论】:
-
但是这些答案还不够这个问题的第一部分:
Does the descriptor parameter in the function necessarily need to be an object?,即defineProperty参数
标签: javascript design-patterns prototype ecmascript-5 defineproperty