this object in JS
阿神
阿神 2017-05-19 10:26:19
0
4
657

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"

阿神
阿神

闭关修行中......

reply all(4)
習慣沉默

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:

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:

  1. First find the nearest this的最近的一个function containing

    ;
  2. functionThen look at the way this

    is called. See here for details.
🎜
滿天的星座
  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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template