I'm trying to understand at which point object member function becomes bound to object instance. In the following example
function F() {
this.foo = 'foo';
};
var f = new F();
f.test = function() {
alert(this.foo);
};
var c = f.test;
f.test();
(f.test)();
var d;
(d = f.test)();
c();
output is "foo"
, "foo"
, undefined
, undefined
( as expected ). If we look at AST for last 4 lines, it looks like this, and is the same MemberExpression argument for direct call and assignment + call
{
"type": "MemberExpression",
"computed": false,
"object": {
"type": "Identifier",
"name": "f"
},
"property": {
"type": "Identifier",
"name": "test"
}
}
So the question is: why can't we read (f.test)()
as two distinct operations - MemberExpression + CallExpression and instead it looks more like a special case in the language "MemberCallEcpression" ( and why AST parsers don't have it as special case )? Why result of f.foo
expression is bound function for function call and unbound for assignment?