var str="hello";
var obj={
str:"world",
saysstr:this.str
};
alert(obj.saystr); / /The result is hello
May I ask why the result is "hello" instead of "world"
漂亮男人2017-05-19 10:28:19
this
指向什么,由包含它的最近的一个function
决定的;
如果没找到function
,那么this
is the global object.
In your question, it’s the latter.
Modify the code slightly:
var str="hello";
var obj={
str:"world",
saystr: function() {
alert(this.str)
}
};
obj.saystr();
This is the first situation.
To summarize: Determining this
usually takes two steps:
First find the nearest this
的最近的一个function
containing
function
Then look at the way this
伊谢尔伦2017-05-19 10:28:19
Convert the question to the following for better understanding:
var str = "hello";
var obj = {};
obj.str = "world";
obj.saystr = this.str;
So you can see at a glance that this points to the window global object, so the result of obj.saystr is hello