In JavaScript, the concept of this is complicated. In addition to object-oriented programming, this is still available everywhere. This article introduces the implicit binding of this. I hope you will like it.
Let's look at an example.
function foo() { console.log( this.a );}var obj = { a: 2, foo: foo};obj.foo(); // 2
This points to obj, because the call-site during foo execution (which can be understood as the scope of the call) is above obj. Note that it has nothing to do with where to declare it during running.
Call-site and call-stack
Call-site refers to the call domain and call-stack refers to the call stack. The following code helps us understand
function baz() { // call-stack is: `baz` // so, our call-site is in the global scope console.log( "baz" ); bar(); // <-- call-site for `bar`}
Bar () is called in baz (), so the bar's call domain is baz. At this time, the bar's call stack is only baz, while baz itself is exposed in the global scope, therefore, its calling domain is also in the global scope.
function bar() { // call-stack is: `baz` -> `bar` // so, our call-site is in `baz` console.log( "bar" ); foo(); // <-- call-site for `foo`}function foo() { // call-stack is: `baz` -> `bar` -> `foo` // so, our call-site is in `bar` console.log( "foo" );}baz(); // <-- call-site for `baz`
After understanding it, I will look back at the example at the beginning. Does it feel much clearer. In fact, this only points to its call-site
There are also the following methods:
Function foo () {console. log (this. a);} var obj2 = {a: 42, foo: foo}; var obj1 = {a: 2, obj2: obj2}; obj1.obj2. foo (); // 42 Implicitly Lost (implicit loss) 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 objectbar (); // "oops, global"
Although bar references foo on obj, it is actually a direct reference to foo, so it will be 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 objectdoFoo( obj.foo ); // "oops, global"