javascript - Why is the result different in the Chrome console and sublime? This in JS -


i'm learning identifier , know when function not called on object refers window object in non-strict mode. result, expect this.bar log "whatever."

"whatever" output when run code in chrome console.it, output undefined when run code using node build system in sublime.

why case? right result in chrome console correct? when else encounter problems this?

here's code

function foo() {     // console.log(this)     console.log( this.bar ); }  var bar = "whatever";   // --------  foo();              // output "whatever" in chrome console , output undefined in sublime's node build system. 

when use this in function without specifying different context, refers global object. in chrome, window object. in node, called global. when specifying different context, be, example, using new constructor, or call , apply functions bind particular this.

the main difference when use var bar = "whatever"; in node, use of var scoping variable module writing, not whole node process. in chrome, scoping global window object. same leaving out var altogether.

i have added couple of examples below regarding scope, make little clearer. playing around in console great way discover things this.

example 1: example 1 can see, calling test() has created globally scope x variable, , this found referring window variable.

example 2: example 2 in example, constructed new instance, creates new scope. x variable not scoped globally. way access use myinstance context.

as problem, have 2 options:

option 1 (recommended): since bar not globally scoped, don't want access global variable using this

var bar = "whatever";  function foo() {     console.log(bar); } 

option 2 (not recommended): set variable in global scope, can either use this or global

global.bar = "whatever";  function foo() {     console.log(this.bar); // console.log(global.bar); } 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -