I have the following code in JSfiddle.
var a = 1;
function five() {
this.a = 5;
console.log(a); //JSfiddle prints the value 1
}
five()
But when I paste the same exact code inside Chrome console, the function five() prints 5. Why?
By default JSFiddle wraps your code in the window.onload event, so you're actually running this:
window.onload = function() {
var a = 1;
function five() {
this.a = 5;
console.log(a); //JSfiddle prints the value 1
}
five()
}
That means that a is local to that function, while this still refers to the global object (window). In the Chrome console, without the wrapper function, var a is creating a global variable, which are created and stored as properties on the global object, and is thus the same as window.a / this.a.
If you go to the JavaScript options and choose either of the "nowrap" options, it will log 5 in JSFiddle too:

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With