Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Trying a closure the wrong way?

I can't figure out what's wrong with the following code and why would it work when I do it using the second way. Can anyone please help me understand this?

I have this following Javascript code:

var clsFunc = function(prefix) {
  var id = 0;
  return function() {
    id = id + 1;
    console.log(prefix + id);
  }
}

First way (did not work):

If I try to call this function like this nothing happens

clsFunc('div') 

Second way (worked)

var getId = {'div': clsFunc('div')}

getId.div()

Result:

div1
undefined
getId.div()

Result:

div2
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...