优艾设计网

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

优艾设计网 https://www.uibq.com 2023-01-11 07:46 出处:网络 作者:PS入门教程
以下几段代码,输出的结果不一样。希望有大神可以解答一下原理,谢谢! var myvar = \"TheWindow\"; var object = { myvar : \"MyObject\", getVar : function(){ return function(){ return myvar; }; } }; console

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

var myvar = "TheWindow"; var object = { myvar : "MyObject", getVar : function(){ return function(){ return myvar; }; } }; console.log(object.getVar()());//输出TheWindowfunction 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属性,但是这样写会报优艾设计网_PS交流错,但是如果写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());

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


0

精彩评论

暂无评论...
验证码 换一张
取 消