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"
闭关修行中......
This article can solve most of this problems.
this指向什么,由包含它的最近的一个function决定的;如果没找到function,那么this is the global object. In your question, it’s the latter.
this
function
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
functionThen look at the way this
alert(obj.saystr); 这句话实际等同于:
alert(this.str);
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
This article can solve most of this problems.
this
指向什么,由包含它的最近的一个function
决定的;如果没找到
function
,那么this
is the global object.In your question, it’s the latter.
Modify the code slightly:
This is the first situation.
To summarize: Determining
this
usually takes two steps:First find the nearest
;this
的最近的一个function
containing
is called. See here for details.function
Then look at the way thisConvert the question to the following for better understanding:
So you can see at a glance that this points to the window global object, so the result of obj.saystr is hello