问一个 ES6 作用域的问题

2020-04-01 15:13:49 +08:00
 jingcoco
var value = 1;

var foo = {
  value: 2,
  bar: function () {
    return this.value;
  }
}

//示例 1
console.log(foo.bar());
//示例 2
console.log((foo.bar)());

为什么这两个结果一样.老感觉第二个结果是 value=1 这个

3318 次点击
所在节点    JavaScript
35 条回复
TabGre
2020-04-01 15:20:03 +08:00
1. this 的隐式绑定
2. this 的隐式绑定回退为默认绑定,非严格模式下 this 为 global(window)
salamanderMH
2020-04-01 15:21:56 +08:00
foo.bar 这个属性就是一个函数,这两种写法一样的,this 还是指向 foo 的。
TabGre
2020-04-01 15:22:57 +08:00
@TabGre LOL,忽略我的回答,我也没有完全搞明白。dog
daquandiao2
2020-04-01 15:23:57 +08:00
ff = foo.bar

ff()
YuxiangLuo
2020-04-01 15:25:39 +08:00
let x = foo.bar;
console.log(x());
这样就是 1

可能是因为 foo.bar 与(foo.bar)是同一个 reference,而 x 是复制的 reference
TabGre
2020-04-01 15:28:25 +08:00
@daquandiao2 这样是不是就打印为 1 了呢?
amaranthf
2020-04-01 15:29:09 +08:00
你这个是运算符优先级问题,不是作用域问题。
wunonglin
2020-04-01 15:41:43 +08:00
你把
bar: function () {
return this.value;
}
换成
bar: () => {
return this.value;
}
有惊喜
jingcoco
2020-04-01 15:44:18 +08:00
刚才搜索了一下 ,又晕了...
```
(false|| foo.bar)()

```
这样结果就是 1 了.....
jingcoco
2020-04-01 15:45:21 +08:00
@wunonglin 你这个我知道为什么, 箭头函数的作用域是执行环境的.
iNaru
2020-04-01 15:52:56 +08:00
@jingcoco 实例 2 中括号中的(foo.bar)返回的是引用,(false|| foo.bar)的则是或运算的结果
weikexin
2020-04-01 16:02:44 +08:00


max21
2020-04-01 16:06:30 +08:00
@jingcoco false|| foo.bar 的运算结果就是 function () {return this.value;},然后执行这个函数,this 指向什么对象是再函数被调用时才确定的,这里没有使用 foo.bar 调用,所以 this 指向全局对象
ming61177
2020-04-01 16:14:56 +08:00
看不出跟 ES6 有什么关系
kuanng
2020-04-01 16:22:31 +08:00
有点意思。我的第一直觉也是 value=1
vivipure
2020-04-01 16:37:18 +08:00
和作用域没关系,主要是 Reference 没变
TabGre
2020-04-01 16:40:06 +08:00
箭头函数的 this 不是调用确定,而是 lexical 确定的把
DowneyLam
2020-04-01 16:56:25 +08:00
跟 Reference 有关 你可以看看这篇文章 https://github.com/mqyqingfeng/Blog/issues/7
ironMan1995
2020-04-01 17:09:33 +08:00
你這問題就和(function() {})() 與 (function(){}())有什麽區別。你這兩個實例都是作爲 foo 對象的方法調用的 this 指向 foo,想要 this 指向全局的 value,將 foo.bar 賦值給一個全局變量然後執行。var bar = foo.bar; bar(); //1 或者使用箭頭函數
Hoshinokozo
2020-04-01 17:10:22 +08:00
结果一样不是正常的吗?这两种写法都是一个意思,结果都是调用 bar 函数,没搞懂疑惑的点在哪

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/658321

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX