user2202911
user2202911

Reputation: 3014

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

Upvotes: 0

Views: 94

Answers (2)

Leonid Beschastny
Leonid Beschastny

Reputation: 51450

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.

Upvotes: 3

Verhaeren
Verhaeren

Reputation: 1661

That behaviour is caused by this:

'use strict';

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

Upvotes: 1

Related Questions