var name = "123";
var object = {
name: "My Object",
getNameFunc: function() {
return this.name;
}
}
console.log(object.getNameFunc()); //My Object
console.log((object.getNameFunc)()); //My Object
console.log((object.getNameFunc = object.getNameFunc)()); //123
Why is the final output 123? What does object.getNameFunc = object.getNameFunc mean?
为情所困2017-06-26 10:57:12
I read the question wrong, let me explain it again.
First look at object.getNameFunc
, its definition is
function () {
return this.name
}
When you write like this object.getNameFunc = object.getNameFunc
, it can actually be seen as like this.
object.getNameFunc = function () {
return this.name
}
In fact, when doing such a thing, this
is no longer an object
. But window
(in the browser). So the output is the external name
.
Probably like this = =
phpcn_u15822017-06-26 10:57:12
The result of the assignment operation is an lvalue.
Therefore (object.getNameFunc = object.getNameFunc)()
can be thought of as:
var f = (object.getNameFunc = object.getNameFunc);
f();
So this
points to the global, so we get 123
天蓬老师2017-06-26 10:57:12
var name = "123";
var obj = {
name: "My Object",
getNameFunc: function() {
return this.name;
}
}
console.log(obj.getNameFunc()); //My Object
console.log((obj.getNameFunc)()); //My Object
console.log((obj.getNameFunc = obj.getNameFunc)()); //123
console.log((obj.getNameFunc = obj.getNameFunc));
Judging from the citation results of this, this must be pointing to the overall situation. Maybe there are some links in the middle that are not understood.
If we add a piece of code at the end, we can know what the content of (obj.getNameFunc = obj.getNameFunc) is. Yes, there is a function in the console, so the statement (obj.getNameFunc = obj.getNameFunc) is executed The result is a function. Inertial thinking leads us to take it for granted that this is just a reassignment operation, and that it is still obj that calls the function.
In fact, after the statement is executed, this function is actually called by the global object.