js this 问题
发布于 10 年前 作者 bingqingwu 4484 次预览 最后一次回复是 10 年前 来自 问答
文件test.js内容如下:
var fruit = "apple";
function test(){
console.log(this.fruit);
}
test();
//console.log(this);
执行 node test.js, 结果为 “undefined”. 修改 var fruit = “apple”; ==> this.fruit = “apple”, 结果为 “undefined”. 修改 var fruit = “apple”; ==> fruit = “apple”, 结果为 “apple”. 如果理解这三种定义的不同? test函数外的this 和 函数内的this 有何不同?
7 回复
This如果没调用者都指全局,我这么理解。node中你的文件好像不是全局。。珍爱生命使用
use strict… 自豪地采用 CNodeJS ionicnode module 实际上是被包含在一个匿名函数中的,上下文并不是全局,搜一下 require 的工作原理。有很多介绍。 var fruit 是一个局域变量,没有主体。不加 var 那是不科学的,会出乱子。 这样的代码太没道理,直接 console.log(fruit) 就是了。为何要加个 this ,纯添乱不是。
var fruit是定义局部,this.fruit是当前context. 直接fruit是在global里,不你使用. 直接test()是传递一个为{}的context.要传递其他的context,可以test.call({fruit:‘hello’});
console.log(this)研究一下呀
@William17 回答挺详细的!这个就是个执行上下文的问题,多琢磨琢磨,搞清楚原理,就比较容易了。node文件应该也是一层context
针对问题做的自我总结: 在node里,js的顶层对象是global; 在global上定义的属性和函数,在任何模块里都可以访问;
.
.
.
.