为什么使用o.getName(),却可以得到?

function makeProperty(o, name) {  

                var value;  

                  

                o["get" + name] = function() {  

                    return value;  

                };  

                  

                o["set" + name] = function(v) {  

                    value = v;  

                };  

            }  

              

            var o = {};  

              

            makeProperty(o, "Name");  

              

            o.setName("Frank");  

              

                        alert(o.getName());  

  

            (function(o) {  

                alert(1);  

                for(a in o) {  

                    alert(a + " = " + o[a]);  

                }  

            })(o);  


这段代码中的那个对象的value值在那里存放着,写的测试代码并没有输出出来,但是用o.getName(),却可以得到!帮忙解答一下,不胜感激。


函数式编程
浏览 138回答 2
2回答

芜湖不芜

js中&nbsp;某个函数的内部函数在该函数执行结束后仍然可以访问这个函数中定义的变量,这称为闭包(Closure)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;function&nbsp;outside()&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;&nbsp;var&nbsp;myVar&nbsp;=&nbsp;1;&nbsp;&nbsp;&nbsp;return&nbsp;function&nbsp;(){&nbsp;&nbsp;&nbsp;alert(myVar);&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;var&nbsp;t&nbsp;=&nbsp;outside();&nbsp;&nbsp;&nbsp;t();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;js中&nbsp;某个函数的内部函数在该函数执行结束后仍然可以访问这个函数中定义的变量,这称为闭包(Closure)&nbsp;&nbsp;&nbsp;下面例子是给三个锚anchor1,anchor2,anchor3添加onclick事件,可以预期的效果是点击锚点显示相应的锚点ID,实际上却都是显示"My&nbsp;id&nbsp;is&nbsp;anchor4",&nbsp;这个就是闭包作用引起的逻辑上的bug,添加事件的函数执行完后i的值为4,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ADS.addEvent(window,&nbsp;'load',&nbsp;function(W3CEvent)&nbsp;{m&nbsp;&nbsp;&nbsp;for&nbsp;(var&nbsp;i=1&nbsp;;&nbsp;i<=3&nbsp;;&nbsp;i++&nbsp;)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;anchor&nbsp;=&nbsp;document.getElementById('anchor'&nbsp;+&nbsp;i);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ADS.addEvent(anchor,'click',function()&nbsp;{&nbsp;&nbsp;&nbsp;alert('My&nbsp;id&nbsp;is&nbsp;anchor'&nbsp;+&nbsp;i);&nbsp;&nbsp;&nbsp;});&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;}); &nbsp;&nbsp;

jeck猫

alert(a + " = " + o[a]); 只是输出方法定义啊&nbsp;alert(a + " = " + o[a]());才是方法调用
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript