Reputation: 1103
// Situation 1
var a = function A() {
this.x = 1;
var b = function B () {
this.x = 2;
console.log('Method B : x = ' + this.x);
};
console.log('Method A : x = ' + this.x);
b();
}
When I call a() , my result is
Method A : x = 1
Method B : x = 2
But if I delete "this.x = 2" as :
// Situation 2
var a = function A() {
this.x = 1;
var b = function B () {
console.log('Method B : x = ' + this.x);
};
console.log('Method A : x = ' + this.x);
b();
}
My result will be
Method A : x = 1
Method B : x = 1
I don't understand why
But
My code runs on Chrome v23
Upvotes: 0
Views: 108
Reputation: 2271
this
is a special keyword in javascript and it depends on the context. In your case function B()
is in the context of function A()
. So if you don't overwrite this.x
in function B()
it'll be the value you assigned in function A()
.
Upvotes: 0
Reputation: 8426
You didn't call b()
until after the value of A was printed. Therefore the value of x was 1 and THEN it was changed to 2 by b.
If you call b()
before printing a()
the output will be
Method A : x = 2
Method B : x = 2
As b()
will first change value then a()
will log
This is the function
var a = function A() {
this.x = 1;
var b = function B () {
this.x = 2;
console.log('Method B : x = ' + this.x);
};
b();
console.log('Method A : x = ' + this.x);
}
Both a and b reference the window object window.x
.
Upvotes: 1
Reputation: 96790
The reason this.x
is being changed in both a
and b
is because they're both referencing the window
object.
I think you're having a misconception with this one; this.x
is being changed after the call to b
. We can see this if we reverse the calls:
b(); // 2
console.log('Method A : x = ' + this.x); // 2
Upvotes: 2
Reputation: 780655
Since, this.x = 2
is in the definition of function B, it doesn't take place until B is called, not when it's defined. Try this version and see:
// Situation 3
var a = function A() {
this.x = 1;
var b = function B () {
this.x = 2;
console.log('Method B : x = ' + this.x);
};
console.log('Method A before B: x = ' + this.x);
b();
console.log('Method A after B: x = ' + this.x);
}
Upvotes: 2
Reputation: 235962
Calling b()
like you do, will result in this
referencing the global object (window
within a browser environment).
That explains your behavior, your're writting basically window.x = 1;
Upvotes: 1