Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.5k views
in Technique[技术] by (71.8m points)

不应该是每次返回的闭包都是n=0吗,++也应该在n=0基础上,输出应该是111啊

当有n++时候,返回值是123

function fun(n, b) {
    console.log(b) //und123
    return {
        fn1: function (m) {
            n++;
            return fun(m, n);
        }
    };
}
var a = fun(0)
a.fn1(1);  
a.fn1(2);    
a.fn1(3); 
function fun(n, b) {
    console.log(b) //und000
    return {
        fn1: function (m) {
            //n++;
            return fun(m, n);
        }
    };
}
var a = fun(0)
a.fn1(1);  
a.fn1(2);    
a.fn1(3); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

a.fn1方法每次调用时都会修改a.fn1的作用域对象属性n的值。Chrome debugger看看:
image.png

image.png

image.png

image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...