It is not the same syntax. JavaScript does not distinguish between methods and functions as values, the distinction is purely in method call. The syntax receiver.method(...args)
(if receiver.method
is a non-arrow function) calls as method, i.e. it will set this
to receiver
during the call. (Equivalently, the syntax receiver[methodname](...args)
will do the same.)
Any other function call syntax is just a function call, without affecting this
. Specifically, (obj2.foo = obj1.foo)
evaluates to just a function, that does not know what receiver it should be addressed to, and consequently this
is the global object, and this.a
the global variable a
.
EDIT: Examples...
window.context = "global";
let foo = {
context: "foo",
fn: function() { console.log(this.context); },
arrow: () => { console.log(this.context); },
}
console.log(this.context); // global object (`window` in browser, `global` in Node)
foo.fn(); // method call syntax; `this` is set to `foo`
foo["fn"](); // equivalent to the above; `this` is set to `foo`
foo.arrow(); // method call syntax but arrow, so doesn't matter; `this` is unchanged
let fnS;
fnS = foo.fn; fnS(); // no receiver, regular function call, `this` is unchanged
(fnS = foo.fn)() // equivalent to the previous one
Of these examples, only the foo.fn()
and foo["fn"]()
will set this
to foo
; all the others will leave it as it was (i.e. this
will be the global object).