function foo() { console.log( this.a ); } var obj = { a: 2, foo: foo }; obj.foo(); // 2
this指向了obj,由于foo执行时
的call-site
(能够理解为调用时所在做用域)在obj
上面。注意是运行的时候,和在哪里声明的没有关系。oop
call-site
姑且理解为调用域
,call-stack
为调用栈
。以下代码能够辅助咱们理解this
function baz() { // call-stack is: `baz` // so, our call-site is in the global scope console.log( "baz" ); bar(); // <-- call-site for `bar` }
在baz()
中调用bar()
,因此bar的调用域是baz,此时bar的调用栈只有baz;而baz自己暴露在全局做用域中,因此它的调用域则也在全局做用域中。code
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`
理解以后再回头看开头的例子,是否是感受清晰了不少。其实this只是指向了它的call-site
ci
还有以下玩法:作用域
function foo() { console.log( this.a ); } var obj2 = { a: 42, foo: foo }; var obj1 = { a: 2, obj2: obj2 }; obj1.obj2.foo(); // 42
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"
虽然bar引用了obj上的foo,但实际上至关因而直接对foo引用而已,因此会默认绑定到全局。it
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"