So... ES6¹ (which happens to be standardized a few hours ago) brings default parameters for functions similar to those in PHP, Python etc. I can do stuff like:
function foo (bar = 'dum') {
return bar;
}
foo(1); // 1
foo(); // 'dum'
foo(undefined); // 'dum'
MDN says that the default value for the parameter is evaluated at call time. Which means each time I call the function, the expression 'dum'
is evaluated again (unless the implementation does some weird optimizations which we don't care about).
My question is, how does this
play into this?
let x = {
foo (bar = this.foo) {
return bar;
}
}
let y = {
z: x.foo
}
x.foo() === y.z(); // what?
The babel transpiler currently evaluates² it as false
, but I don't get it. If they are really evaluated at call time, what about this:
let x = 'x from global';
function bar (thing = x) {
return thing;
}
function foo () {
let x = 'x from foo';
return bar();
}
bar() === foo(); // what?
The babel transpiler currently evaluates³ it as true
, but I don't get it. Why does bar
not take the x
from foo
when called inside foo
?
x.foo === y.foo
which is clearlyfalse
, because in both cases you are calling thefoo
function, but in the first case,this === x
and in the second case,this === y
. The question seems to really be, why is essentiallylet x = {foo(){ return this; }}; let y = {z: x.foo}; y.foo() === y
. The answer is becausey.foo()
is the same as doingy.foo.call(y)
. That is howthis
is defined. – Vano