关于this的困惑

1.阅读《你不知道的javascript》是里面有段代码如下:

function foo() {

  var a = 2;
  this.bar();

}

function bar() {

  console.log(this.a);

}

foo();

作者说this.bar()是引用不到bar()函数,调用bar()应省去前面的this。而在接下来的2.2.1节中作者又举了例子:

function foo() {
      console.log(this.a)
}
var a = 2
foo()//2

这里this.a却没问题。

2.我的困惑是:foo调用时是默认绑定,foo中的this应绑定到全局,而全局中有bar函数,所以this.bar()应该可以引用到bar函数。那么作者说的foo中的this.bar()引用不到bar()函数又该如何理解?还请大家不惜赐教,非常感谢!

阅读 3.3k
6 个回答

应该是是说 this 不是指foo 作用域吧,所以this.a不是2
或者说是 use strict

this.bar()是引用不到bar()函数,调用bar()应省去前面的this。

其实,this.bar() 是否能调用成功,取决于环境。你可以试下,在 Chrome console 里面是没问题的,因为全局声明的 function 都放在了 Window 底下。但在 NodeJS 中就不行。

foo调用时是默认绑定,foo中的this应绑定到全局,而全局中有bar函数,所以this.bar()应该可以引用到bar函数

同理,取决于环境


另外,就算你的 foobar 是被绑定到了 Window 对象中,a 也是不会绑定上去的,因为 a 是在 foo 里面用 var 声明的。。所以 console.log(this.a) 肯定会输出 undefined

作者应该是指的是在严格模式下,this指向的是undefined。
在非严格模式下两个函数的this都是指向window的。this.bar()是可调用的,返回的结果是undefined(因为a为foo的局部变量,在全局下是访问不到的).

好吧,都怪我英文不好!谢谢大家的回答!

这是中文翻译:

   这段代码中的错误不止一个。虽然这段代码看起来好像是我们故意写出来的例子,但是实际上它
出自一个公共社区中互助论坛的精华代码。这段代码非常完美(同时也令人伤感)地展示了 this 多
么容易误导人。
   首先,这段代码试图通过 this.bar() 来引用 bar() 函数。这是绝对不可能成功的,我们之后会解释原
因。调用 bar() 最自然的方法是省略前面的 this ,直接使用词法引用标识符。
   此外,编写这段代码的开发者还试图使用 this 联通 foo() 和 bar() 的词法作用域,从而让 bar() 可以
访问 foo() 作用域里的变量 a 。这是不可能实现的,你不能使用 this 来引用一个词法作用域内部的东
西。

这是英文:

   There’s more than one mistake in this snippet. While it may seem
contrived, the code you see is a distillation of actual real-world code
that has been exchanged in public community help forums. It’s a won‐
derful (if not sad) illustration of just how misguided  this assumptions
can be.
   First, an attempt is made to reference the  bar() function via
this.bar() . It is almost certainly an accident that it works, but we’ll
explain the how of that shortly. The most natural way to have invoked
bar() would have been to omit the leading  this. and just make a
lexical reference to the identifier.
   However, the developer who writes such code is attempting to use  this
to create a bridge between the lexical scopes of  foo() and  bar() , so
that  bar() has access to the variable  a in the inner scope of  foo() . No
such bridge is possible. You cannot use a  this reference to look some‐
thing up in a lexical scope. It is not possible.

第一个this代指的是foo,并不是window,所以this.bar并没有指定到window上的bar方法;
第二个是因为console是window上的对象,在定义时已经做过处理,console里面的this都统一为window。所以能获取到外部定义的对象。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题