user3719857 user3719857 - 4 months ago 19
Javascript Question

Use of setter and Object.create();

I'm currently reading the series of books You don't know JS. In one of the books it's written :


If a foo is found higher on the [[Prototype]] chain and it’s a setter
(see Chapter 3), then the setter will always be called. No foo will be
added to (aka shadowed on) myObject, nor will the foo setter be
redefined.


Now I tried the following code:

var a = {
set t(tet) {
this._t_ = tet;
},
get t() {
return this._t_ ;
}
};

a.t = 5;
var b = Object.create(a);
b.t = 4;
console.log(a.t);
console.log(b.t);


For my suprise the logs print out
5
and
4
in that order. From what is written in the book I expect to see two
4
being printed, but it seems there is actually shadowing. Why is that ?




Thanks to the answer by Quentin, this is actually the code that demonstrates the functionallity I wanted :)

var a = {
t : undefined,
set t(tet) {
t = tet;
},
get t() {
return t ;
}
};

a.t = 5;
var b = Object.create(a);
b.t = 4;
console.log(a.t);
console.log(b.t);

Answer

The 4 and 5 are stored in _t_ on the two different objects, not in t.

t is still the setter and getter in both cases (although the value of this varies because it is called in the context of two different objects).

Comments