Reputation: 303
I have the following function. The javascript tutorial I'm reading says it should output 2, but I'm getting undefined in my text editor (JS Fiddle).
What could be the reason? Does this have something to do with strict mode vs non-strict mode?
function foo(){
console.log( this.a );
}
var a = 2;
foo(); //should output "2" but I'm getting undefined. Why?
Upvotes: -1
Views: 61
Reputation: 700730
That's because you are running the code in a function wrapper that JSFiddle creates. The default is onLoad
which puts the code in a function that runs on the load event.
That makes the a
variable local to that function, and not a global variable. When you try to access it using this.a
it will look for the variable in window.a
(as this
will point to the window
object), but as the variable is not global it can't be found there.
If you choose No wrap - in <head>
or No wrap - in <body>
for where to put the code, you will get the 2
as output.
Upvotes: 3
Reputation: 437734
The tutorial probably assumes that this code is going to be executed in the context of the global object, in which case it will indeed print 2. You can copy/paste the snippet in your browser console and you can see for yourself that the output is 2.
However, if you put the code inside a function and then execute that function, the code will print undefined
. I'm not 100% sure of the fine points of how JSFiddle works, but in your case this is what is happening: it puts the code inside a function on your behalf.
Upvotes: 0
Reputation: 2742
When you call this.a
you are looking for a property in the foo
functions prototype. Defining var a = 2
is simply just making a new var called a
.
What you want to do is inside foo put this.a = 2
and then your console will output properly. Alternativly, if you want to assign the value of a outside the function
var foo = new foo();
foo.a = 2;
console.log(foo.a);
Feel free to ask me questions!
Upvotes: -1