The clsFunc
function creates a function and returns it. So just doing
clsFunc('div');
...is pointless, because it creates a function and then just throws it away, because you didn't store it anywhere.
The second way stores the function that was created in an object property. That function has a reference to the context that created it (the call to clsFunc
), even though that call has returned, which contains the id
variable. When you call the function (getId.div()
), it adds 1 to id
and then outputs the prefix ("div"
) followed by the new value if id
(1, then 2, then, 3, etc.).
You don't need an object for your second way, you could just use a variable:
var clsFunc = function(prefix) {
var id = 0;
return function() {
id = id + 1;
console.log(prefix + id);
}
};
var f = clsFunc('div');
f(); // "div1"
f(); // "div2"
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…