Let's say we have an object with a function property, and this function uses this:
let o = {
a: function() {
return `a, ${this.b}`;
},
b: 'b'
};
I understand that we'll see 'a, b' for the following piece of code:
let o = { a: function() { return `a, ${this.b}`; }, b: 'b' };
console.log(o.a());
This is because javascript considers the in-place "topology" of o.a(...) to mean that o ought to be set as this within this occurence of o.a's execution.
I also understand that the following produces 'a, undefined':
let o = { a: function() { return `a, ${this.b}`; }, b: 'b' };
let f = o.a;
console.log(f());
This is because the "topology" of f(...) tells javascript that there is no explicit this.
For this reason I was surprised that the following produces 'a, b':
let o = { a: function() { return `a, ${this.b}`; }, b: 'b' };
console.log((o.a)());
It looks to me like using parentheses around (o.a) should force javascript to resolve o.a to an unbound, this-less function, before going any further.
For completeness, this example successfully unbinds the instance of the function call:
let o = { a: function() { return `a, ${this.b}`; }, b: 'b' };
let f = () => 'f';
console.log((o.a || f)());
Even though the || short-circuits on the first operand, there's still a difference between (o.a) and (o.a || f).
- How should I comprehend javascript's logic to determine the value of
this? - Are there any other unintuitive examples related to these?
- Is there any better or more official vocabulary I can use to describe what's going on here?
Thanks!