javascript对象、this、作用域和闭包的问题。(相同变量名查找问题) 财富值54

2016-10-29 11:43发布

以下几段代码,输出的结果不一样。希望有大神可以解答一下原理,谢谢!

var myvar = "TheWindow"; var object = {     myvar : "MyObject",     getVar : function(){         return function(){             return myvar;         };     } }; console.log(object.getVar()());//输出TheWindow  function MyCont(){     var myvar = "MyObject";     this.getVar = function(){         return function(){             return myvar;         };     } } var obj = new MyCont(); console.log(obj.getVar()());//输出MyObject

然后我修改了一下,加上了this,输出结果又不同了。

var myvar = "TheWindow"; var object = {     myvar : "MyObject",     getVar : function(){         return function(){             return this.myvar;//此处加入了this,依旧输出TheWindow         };     } }; console.log(object.getVar()()); function MyCont(){     var myvar = "MyObject";     this.getVar = function(){         return function(){             return this.myvar;//此处加入了this,输出变成了TheWindow,而不是原先的MyObject         };     } } var obj = new MyCont(); console.log(obj.getVar()());

然后我再改一下

var myvar = "TheWindow"; var object = {     myvar1 : "MyObject",     getVar : function(){         return function(){             return myvar1;//虽然object内含有myvar1属性,但是这样写会报错,但是如果写this.myvar1的话就不报错,输出undefined         };     } }; console.log(object.getVar()());   var myvar = "TheWindow"; var object = {     myvar : "MyObject",     getVar : function(){           return myvar;//此处去掉了function,还是输出TheWindow     } }; console.log(object.getVar());   var myvar = "TheWindow"; var object = {     myvar : "MyObject",     getVar : function(){           return this.myvar;//对比上面,加入了this,则输出的是对象属性MyObject     } }; console.log(object.getVar()); 

最后还是要感谢一下,好心人帮忙解答问题,万分感谢!

友情提示: 问题已经关闭,关闭后问题禁止继续编辑,回答。