Let's look at an example first.
function foo () {
console.log (THIS.A);
}
var obj = {
a:2,
foo:foo
};
Obj.foo (); 2
This points to obj because the call-site at Foo execution (which can be understood as the scope of the call) is above obj. Note that it is not a matter of when to run, and where to declare it.
Call-site and Call-stack
Call-site is understood as calling the domain, Call-stack for the call stack. The following code can help us understand
function Baz () {
//Call-stack is: ' Baz '
//So, our call-site are in the global scope
console.log ("Baz"); C15/>bar (); <--call-site for ' bar '
}
Call Bar () in Baz (), so the call domain for bar is Baz, and the call stack for bar is only Baz, and Baz itself is exposed to the global scope, so its calling domain is also in the global scope.
function Bar () {
//Call-stack are: ' Baz '-> ' bar '
/So, we call-site is in ' Baz '
console.log ("Bar");
foo (); <--call-site for ' foo '
}
function foo () {
//Call-stack are: ' Baz '-> ' bar '-> ' foo '
/So, ou R Call-site is in ' Bar '
console.log ("foo");
}
Baz (); <--call-site for ' Baz '
Understanding and then looking back at the beginning of the example is not a lot clearer. This is actually just pointing to its call-site
There are also the following:
function foo () {
console.log (THIS.A);
}
var obj2 = {
a:42,
foo:foo
};
var obj1 = {
a:2,
obj2:obj2
};
Obj1.obj2.foo ();
implicitly Lost (implicitly lost)
function foo () {
console.log (THIS.A);
}
var obj = {
a:2,
foo:foo
};
var bar = Obj.foo; function reference/alias!
var a = "oops, global"; ' A ' also property on global Object
Bar ();//"Oops, global"
Although bar refers to Foo on obj, it actually corresponds to a direct reference to Foo, so it is bound to the global by default.
function foo () {
console.log (THIS.A);
}
function Dofoo (FN) {
//' FN ' is just another reference to ' foo '
fn ();//<--call-site!
}
var obj = {
a:2,
foo:foo
};
var a = "oops, global"; ' A ' also property on global object
Dofoo (Obj.foo);//"Oops, global"