Thursday, 15 January 2015

javascript - Setting inherited property via setter -



javascript - Setting inherited property via setter -

i have code:

// 'vehicle' object constructor function vehicle() { this.wheels = 4; } // adding 'setwheels' setter function set 'wheels' property object.defineproperty(vehicle.prototype, "setwheels", { set: function(x) {this.wheels = x} }); // 'car' object constructor 'vehicle' prototype function car() {} car.prototype = new vehicle; car.prototype.constructor = car; // mycar inherits 'wheels' property , 'setwheels' method mycar = new car(); mycar.setwheels = 2;

i expecting mycar.setwheels = 2 alter inherited property, instead sets mycar's local property shadows inherited one. have read here setting inherited property via setter possible, means doing wrong. exactly?

i expecting mycar.setwheels = 2 alter inherited property, instead sets mycar's local property shadows inherited one

well, you've "called" setter on mycar, setting .wheels property.

if wanted alter inherited property, need alter on object inherited:

car.prototype.setwheels = 2;

(although i've never seen auto 2 wheels)

notice you'd expect instance properties (.wheels set in vehicle) apparent on instances (like mycar), not on prototypes. might consider changing way of inheritance commonly accepted one.

the quote have read @ mdn:

setting property object creates own property. exception getting , setting behavior rules when there inherited property getter or setter.

means own property generated on assignment when there no setter (but info property or not existing yet). if property gets assigned has setter defined (either own or inherited), setter function invoked instead.

indeed, in example, no own .setwheels property getting created on mycar.

what setter function does whole different question. can create property (like yours does, assigning .wheels on current instance, this), or else; including crazy things redefining itself.

to "expected" behaviour, utilize local variable store number of wheels , utilize setter/getter property it:

function car() {} var w = 4; // "local", in iife object.defineproperty(car.prototype, "wheels", { set: function(x) { w = x; // no property changes/creations involved }, get: function() { homecoming w; } }); // yourcar inherits 'wheels' var yourcar = new car(); yourcar.wheels; // 4 yourcar.wheels = 2; // you've got odd auto var mycar = new car(); mycar.wheels; // 2 - what's wrong car?!

here, there 1 property - car.prototype.wheels. assigning .wheels on car instances phone call shared setter, updates shared variable. notice such behaviour undesirable, don't want 1 instance impact others.

javascript inheritance

No comments:

Post a Comment