
var name = "this windos"; var object = { name : "my object", getnamefunc : function () { return function () { return this.name; }; } }; var reslut = object.getnamefunc(); console.log(object.getnamefunc()()); console.log(reslut); console.log(reslut.toString()); console.log(reslut()); console.log(object.name); console.log(name);``` 在看高程3 关于 this 在闭包中介绍 如上代码 我在终端用 node 跑范例代码 结果 浏览器 和 node 给出了不同的答案 在 node 7.7.2 结果 undefined [Function] function () { return this.name; } undefined my object this windos 在 chrome 57.0.2987.98 (64-bit) this windos function () { return this.name; } function () { return this.name; } this windos my object this windos 1 yangff 2017-03-20 12:11:22 +08:00 因为 window 刚好有 name 罢了…… 不信你换成 fuckedName 试试 |
2 yangff 2017-03-20 12:11:49 +08:00 哦看错了…… |
3 yangff 2017-03-20 12:12:55 +08:00 好像我在 node 上跑出来的结果和你不一样哇 |
4 morethansean 2017-03-20 12:15:26 +08:00 有什么问题吗?你想问啥? |
5 morethansean 2017-03-20 12:21:22 +08:00 没注意你 node 的结果……你怎么跑出来的? |
6 SuperMild 2017-03-20 12:24:43 +08:00 闭包和 this 不能混为一谈。闭包只涉及变量,而 this 不是变量。 this 有另一套规则,不适用于闭包的规则。 |
7 SuperMild 2017-03-20 12:30:29 +08:00 正因为有时候 this 比较不好确定,所以才有了利用闭包 that = this 这样的做法。 |
8 Niphor 2017-03-20 13:26:22 +08:00 因为 node 没全局 window ,他是 global 第一句 var name 并不会把 name 挂在 global 上... |
9 Niphor 2017-03-20 13:29:30 +08:00 用 var 似乎会把 scope 指定在当前 module 中, node 运行 js 文件 每个文件都是一个闭包 好像 |
10 Cynic222 2017-03-20 13:39:06 +08:00 你肯定看错了 Node 的输出,console.log 的输出总是以 undefined 结束 |
12 otakustay 2017-03-20 14:36:09 +08:00 你只要记住一点, node 里你写的 js 代码不是在全局跑,而是变成了一个函数的函数体,在这个函数里跑的就行,像__dirname 、 require 之类的都是这个函数的参数 |
13 otakustay 2017-03-20 14:37:21 +08:00 最简单的办法,写个 js : console.log(arguments.callee.toString()); 然后运行下看结果: function (exports, require, module, __filename, __dirname) { console.log(arguments.callee.toString()); } |
15 libook 2017-04-06 23:51:25 +08:00 node 里的全局对象是 global 吧,而且 node 里的作用域是按照 module 隔离的, var 声明的对象只存在于一个 module 内。。。 话说为了避免歧义和 BUG ,已经半年多不用 var 了,项目上已经用 ESLint 严格要求禁止出现 var 指令了。。。 |