search

Home  >  Q&A  >  body text

this object in JS

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"

阿神阿神2753 days ago662

reply all(4)I'll reply

  • 習慣沉默

    習慣沉默2017-05-19 10:28:19

    This article can solve most of this problems.

    reply
    0
  • 漂亮男人

    漂亮男人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:

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

      ;
    2. functionThen look at the way this

      is called. See here for details.
    🎜

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-19 10:28:19

      alert(obj.saystr);
    这句话实际等同于:
    
     alert(this.str);

    reply
    0
  • 伊谢尔伦

    伊谢尔伦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

    reply
    0
  • Cancelreply