var str="hello";
var obj={
str:"world",
fun:function(){
alert(str);
}
}
obj.fun(); //结果是hello
Why the result is hello, not world
滿天的星座2017-05-19 10:30:18
var str="hello";【这个str,obj对象里可以读取】
var obj={
str:"world";
fun:function(){
alert(str);【这个str指obj外部str是【window.str简写】,想要弹出"world"需要使用,this.str,指定作用域。】
}
}
PHPz2017-05-19 10:30:18
var str="hello";
var obj={
str:"world",
fun:function(){
alert(str) //window.str => 'hello'
alert(this.str) // obj.str => 'world'
}
}
高洛峰2017-05-19 10:30:18
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".
ringa_lee2017-05-19 10:30:18
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.
PHP中文网2017-05-19 10:30:18
var str="hello";
var obj={
str:"world",
fun:function(str){
console.log(window.str,this.str,str);
}
}
obj.fun('!') //hello world !
Do you understand?