This is an interview question! And I can't know the reason of it!
function fun(val) {
this.x = val;
return this;
}
var x = fun(1);
var y = fun(2);
console.log(x.x); //I can't understand this result.
console.log(y.x);
This is an interview question! And I can't know the reason of it!
function fun(val) {
this.x = val;
return this;
}
var x = fun(1);
var y = fun(2);
console.log(x.x); //I can't understand this result.
console.log(y.x);
Well, I think that happens because "This" in the fun function refers to Window object not a local thing inside the function. so therefore you first call it by fun(1) and make the window.x = 1, and then call it by fun(2) and it becomes window.x = 2 .. then you console log it when both x and y are a reference to window ... and therefore both will have the same final value.
When you call a function the "normal" way, the this object points to the global object (window):
function testFunction () {
return this;
}
console.log(window === testFunction());
This means that what your function returns is the global object, and both variables x and y are references to the global object. Before it returns, it assigns a property x to the global object.
In the first function call, it assigns 1 to the property x of the global object. In the second function call, it assigns 2 to the same property. This is why you get 2 two times.
If you want this to refer to another object than the global one, you have to use call:
function testFunction (value) {
this.x = value;
return this;
}
var firstObject = {};
var secondObject = {};
var x = testFunction.call(firstObject, 1);
var y = testFunction.call(secondObject, 2);
console.log(x.x);
console.log(y.x);
console.log(x === firstObject);
console.log(y === secondObject);
console.log(window === testFunction());