javascript scope chain
阿神
阿神 2017-05-19 10:28:18
0
5
542
var str="hello";
var obj={
   str:"world",
   fun:function(){
       alert(str);
       }
}
obj.fun(); //结果是hello

Why the result is hello, not world

阿神
阿神

闭关修行中......

reply all(5)
滿天的星座
var str="hello";【这个str,obj对象里可以读取】
var obj={
str:"world";
fun:function(){

   alert(str);【这个str指obj外部str是【window.str简写】,想要弹出"world"需要使用,this.str,指定作用域。】
   }

}
PHPzhong
var str="hello";
var obj={
str:"world",
fun:function(){
   alert(str) //window.str => 'hello'
   alert(this.str) // obj.str => 'world'
  }
}
小葫芦

Because the str:"world" written in your obj object means obj.str="world". This is a property, not a variable. What pops up in the last obj.fun() you ran is the str variable, not an attribute (of course this is also an attribute of the global window). So you understand? If you alert this.str or obj.str you can get "world".

左手右手慢动作

The variable str is actually an attribute of window and has nothing to do with the str attribute of the obj object. This does not involve scope chain issues. What you understand should be the following:

var str="hello";
function change(){
    str="world";
    alert(str)
}
change();

In this example, the global variable str is first reassigned in the function change. When you want to execute alert(str), you look for the variable str at the starting point of your own scope chain, that is, in your own variable object. If you find that it is not found, continue up. Level 1 search found the str variable, but at this time str has been reassigned to world, so world will pop up.

洪涛
var str="hello";

var obj={
str:"world",
fun:function(str){
   console.log(window.str,this.str,str);
  }
}

obj.fun('!') //hello world !

Do you understand?

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