Trying A Closure The Wrong Way?
Solution 1:
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;
returnfunction() {
id = id + 1;
console.log(prefix + id);
}
};
var f = clsFunc('div');
f(); // "div1"f(); // "div2"
(The undefined
s you're seeing are just because you're running this in a JavaScript console that shows you the result of calling the function; since the function doesn't return anything, the result of calling it is undefined
.)
Post a Comment for "Trying A Closure The Wrong Way?"