Reputation: 31
In this code:
function calc(){
this.a = 5;
}
calc(); // Run the function once
// Redefine the function
function calc(){
return this.a;
}
// Re-run the function
calc();
// 5
From a guy coming from Java background.
How is this.a valid (if a hasn't been defined before?)
From what I know, this.a should refer to the instance variable a
of the class ?
Why did it return 5
?
Upvotes: -1
Views: 59
Reputation: 270
"this" value depends on how function was called. Inside a global function (like your example) value of "this" is equal to window object. Which means your two functions are just working with window.a (which will in your case have a value of 5).
Here you can find more information https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
Upvotes: 2
Reputation: 36349
@bknights is correct. To get the behavior you're expecting, you need to new
the function.
function calc(){
this.a = 5;
}
var c = new calc();
console.log(c.a); // will return 5.
c.a = 10;
console.log(c.a); // will return 10
var b = new calc();
console.log(b.a); // will return 5 again
Upvotes: 0
Reputation: 15447
I'm thinking you must have run your first calc before you defined and ran your second calc. In the first one you are initializing member a of the global object. In the second you are returning global.a (the global object is generally the window if you are running on a browser).
You have no class defined
Upvotes: 2