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 :
- isn't
thiskeyword in standalone function referswindow? - if yes, isn't code inside function same
window.a = 5, value ofashould updated5? - if no, why
console.log(this)results in window, value ofa(which global) isn't updated ?
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
thisinsidefrefers global object, case iffexecutedf(), not bound, or bound global objectfnot in strict mode.
Comments
Post a Comment