替换和原始函数var之间的区别



感谢您的帮助。很抱歉不知道我使用的概念的确切名称。

我有这样的功能。

var counter = function() {
var count = 0;
function changeCount(number) {
count += number; 
}
return {
increase: function() {
changeCount(1);
},
decrease: function() {
changeCount(-1);
},
show: function() {
alert(count);
}
}
};

现在,我要用这个函数做"3",似乎有两种方法。

1(

counter().increase()
counter().increase()
counter().increase()
counter().show()

我猜这会抛出"3",但答案是"0"。

2(

var another = counter();
another.increase();
another.increase();
another.increase();
another.show()

现在它返回"3"作为答案。这是我的问题。从字面上看,变量"other"与"counter(("完全相同。那么,为什么答案会有所不同呢?

前一个代码(counter((.inrease(((似乎在"counter(((.increase(("的每3行之后将"count"返回到"o"。而"other.increase(("似乎是对变量"count"的变化进行累积。两个代码之间的区别只是说"变量'other'与counter((相同"。为什么这会导致如此不同的答案?

看看计数器函数的作用。

它创建一个变量,将其设置为0,然后返回一些函数。

若你们打一次电话给柜台,它就会打一次。如果你叫它三次,它就会叫三次。

(然后对返回值调用.increase()…在第一个示例中,这是三个不同的东西,但在第二个示例中每次都是相同的东西(。


或者换一种说法。

如果,每次你打电话给counter,你都会拿一张干净的纸放在你面前。每次你打电话给increase,你都会在面前的纸上画一个勾号。

你要么得到三张纸,每张纸上都有一个记号,要么得到一张纸,上面有三个记号。

我看到这个问题已经得到了回答,但为了澄清(因为我已经键入了(:

counter每次都返回一个新对象,每个对象都有自己的函数声明(递增、递减、显示(。因此,每次调用counter((时,都会得到该对象的一个新的独立实例,并且它的函数不存在于该实例的范围之外。

所以:

// this:
counter().increase();
// is the equivalent of this:
const c1 = counter();
c1.increase();
// and if you do it repeatedly:
counter().increase(); // new instance
counter().increase(); // new instance
counter().increase(); // new instance
counter().show(); // new instance
// you're effectively doing:
const c1 = counter();
c1.increase();
const c2 = counter();
c2.increase();
const c3 = counter();
c3.increase();
const c4 = counter();
c4.show();
// whereas this calls increase() three times on the same object:
const another = counter();
another.increase();
another.increase();
another.increase();

这可能只是使用"(("的区别(('表示要执行(或打开(括号前的变量或函数。

像这个一样调整代码

var counter = (function() {
var count = 0;
function changeCount(number) {
count += number; 
}
return {
increase: function() {
changeCount(1);
},
decrease: function() {
changeCount(-1);
},
show: function() {
alert(count);
}
}
})();
counter.increase()
counter.increase()
counter.increase()
counter.show()

然后返回"3"。唯一的区别是使用了"(("。如果你不使用"((",就意味着你不会执行它。所以你可以处理已经打开的上下文。

最新更新