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