mardi 19 septembre 2017

defineProperty descriptor Parameter and Object.prototype dilemma

I am using defineProperty to create an object properties,.Does the descriptor parameter in the function necessarily need to be an object. Here is the code:

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

I have below two code pieces, where I am making a constructor and then creating objects using it.Both the codes return the same output in console. Does using .prototype.Methodname change anything?

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

The code usage is as follows:

var civicSport= Object.create( person );

defineProp(civicSport, "topSpeed", "120mph");//function created above
console.log(civicSport);

Aucun commentaire:

Enregistrer un commentaire