akotch
akotch

Reputation: 215

Differences in execution between WebStorm and console

When running this code in WebStorm

function sayNameForAll() {
  console.log(this.name);
}

var person1 = {
  name: "Nick",
  sayName: sayNameForAll
};
var person2 = {
  name: "Greg",
  sayName: sayNameForAll
};

var name = "michael";

person1.sayName();
person2.sayName();

sayNameForAll();

It prints out the following

Nick
Greg
undefined

but when running it in the console it prints out

Nick
Greg
Michael 

What causes this difference?

Upvotes: 1

Views: 30

Answers (2)

Luca Kiebel
Luca Kiebel

Reputation: 10096

In the browser there is a window object to which all variables created by scripts are a property of, thus in the browser this.name is "actually" window.name since this is referring to the window in function scope.

Now WebStorm runs this code as if it were a NodeJS application, this is great since WebStorm doesn't need to run a browser in the background and can simply use any node interpreter in the PATH variable. NodeJS however has no window object to which all variables are a property of, so it can't find this.name. this refers to the module which is empty since you are not inside of a module.

Upvotes: 2

m1gu3l
m1gu3l

Reputation: 773

WebStorm runs code in nodejs. Global context (this) refers to module and is an empty object, so property "name" is undefined.

If you run this code in a browser, global context (which is equal to window in this case) and global scope are somewhat mixed, because of legacy reasons.

Those are two different environments. You can add "use strict" at the beginning to make your code behave in more predictable way, but there still will be some differences.

Upvotes: 2

Related Questions