[英]Difference between value of 'this' in client-side vs server-side javascript
Writing a few nodejs test programs and am running into a few unexpected quirks. 编写一些nodejs测试程序,并遇到了一些意外的怪癖。 In the browser when I say console.log(this);
在浏览器中当我说console.log(this);
and it is not in a function, it is the window.object. 它不在函数中,而是window.object。 I know that nodejs has a global object but when I do console.log(this) I simply get an empty object. 我知道nodejs有一个全局对象,但是当我执行console.log(this)时,我只是得到一个空对象。 Then when I ask for the value of 'this' inside a function I created I get undefined
. 然后,当我在创建的函数中要求“ this”的值时,我得到的是undefined
。 I expected to get a reference to the current function (myClass, in this case) What is going on here? 我希望获得对当前函数的引用(在本例中为myClass),这是怎么回事?
See my following nodejs program: 请参阅我的以下nodejs程序:
'use strict';
var log = console.log;
log(this); //empty object
function myClass() {
log (this); //undefined
this.variable = 3; //exception, cannot set property 'test' of undefined
}
myClass();
Thanks 谢谢
Actually, node.js
behaves correctly here, because you're not constructing a class, just calling it's constructor without any this
context. 实际上, node.js
在这里的行为正确,因为您没有构造一个类,只是在没有任何this
上下文的情况下调用它的构造函数。 To create new instance of a class you should always use new
operator: 要创建类的新实例,应始终使用new
运算符:
new myClass();
The difference in behavior is caused by strict mode , because in strict mode, due to security reasons, this
is not referencing the global object by default . 在行为上的差异是造成严格模式 ,因为在严格模式下,由于安全方面的原因, this
是不引用默认的全局对象 。
That behaviour is caused by this: 该行为是由以下原因引起的:
'use strict';
If you use that code in client-side you will have the same behaviour. 如果在客户端使用该代码,您将具有相同的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.