简体   繁体   中英

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. In the browser when I say console.log(this); and it is not in a function, it is the window.object. I know that nodejs has a global object but when I do console.log(this) I simply get an empty object. Then when I ask for the value of 'this' inside a function I created I get undefined . I expected to get a reference to the current function (myClass, in this case) What is going on here?

See my following nodejs program:

'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. To create new instance of a class you should always use new operator:

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 .

That behaviour is caused by this:

'use strict';

If you use that code in client-side you will have the same behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM