javascript - Why this keyword is not referring to window in a stand alone JS function -


i trying scoping , keyword in js, while writing below code got confused expecting console.log(a) after calling f() 5, instead gave me 10.

my question :

  1. isn't this keyword in standalone function refers window ?
  2. if yes, isn't code inside function same window.a = 5 , value of a should updated 5?
  3. if no, why console.log(this) results in window, value of a (which global) isn't updated ?

js fiddle

var = 10;  function f(){     this.a = 5;     console.log(a); }  console.log(a); f(); console.log(a); 

if code run in global scope, produce result expect. problem jsfiddle not run in global scope. hence var a; creates local variable a, while this.a refers global variable a.

here code run in global scope: http://jsfiddle.net/grayoork/ (note "no wrap - ...") setting.

reference: mdn - this.


so both var a; , this.a refer same variable iff:

  • the code runs in global scope
  • this inside f refers global object, case if
    • f executed f() , not bound, or bound global object
    • f not in strict mode.

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -