// 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
- In situation 2 : "this" of function B is referenced to "this" of function A
But
- In situation 1 : "this.x" of function A isn't changed when assign "this.x = 2" in function B
My code runs on Chrome v23
5 Answers 5
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);
}
Comments
The reason
this.xis being changed in bothaandbis because they're both referencing thewindowobject.I think you're having a misconception with this one;
this.xis being changed after the call tob. We can see this if we reverse the calls:b(); // 2 console.log('Method A : x = ' + this.x); // 2
Comments
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;
1 Comment
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.
Comments
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().