javascript - 关于this的困惑
怪我咯
怪我咯 2017-04-11 12:35:22
[JavaScript讨论组]

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()函数又该如何理解?还请大家不惜赐教,非常感谢!

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(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.
大家讲道理

可以看下这个详细介绍JavaScript this 到底指向什么?,希望对你有帮助

怪我咯

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号