1

many people said that looping function inside each() is bad practices.

it will cause terrible perfomance...

just like version one...

Version one :

$(".next").each(function() {

    var el    = $(this),
        setNo = 0,
        onNo  = function() {

            setNo = 1;

        };

    onNo(); // setNo will become 1

)};

so, i have to move function outside each(). then i'm confused on replacing local variable at each()

Version two :

var onNo = function() {

    var setNo = 1;

    return setNo; // replace it

};

$(".next").each(function() {

    var el    = $(this),
        setNo = 0; 

    onNo(); // it's not replacing setNo local variable. how to fix this?

)};

how to fix this?

do you guys have more efficient design pattern, i'm really confused at javascript design pattern.

thanks...

Ching Ching
  • 1,029
  • 4
  • 19
  • 33
  • 4
    "Terrible performance" is a bit of a hyperbole: in 99.9% of use cases it makes absolutely no difference if the loop is one millionth of a second faster or slower per iteration. Performance shouldn't be the reason for choosing a pattern unless a) the code is actually performance-critical and b) you've confirmed it actually makes any practical difference. – JJJ May 15 '16 at 15:52
  • Not sure that there is really difference (in terms of performance) between your two examples? (would like explanation, too) Regarding vars you try to use/change, i guess this could help: http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – sinisake May 15 '16 at 15:56

2 Answers2

3

Are you looking for something like this?

function onNo ($el) {
    // do some calculation with $el
    var setNo = 1;
    return setNo;
}

$(".next").each(function() {

    var $el = $(this)
    var setNo = 0

    setNo = onNo($el)
)}
Daniel Diekmeier
  • 3,401
  • 18
  • 33
2

I agree with Juhana's comment that the performance issues are not significant enough to worry about. However, to answer your question:

You can't set a local variable in another function like that. However, you can pass variables to that function.

var onNo = function(setNo) {

    return setNo; // returns 0

};

$(".next").each(function() {

    var el    = $(this),
        setNo = 0; 

    onNo(setNo);

)};
James Long
  • 4,629
  • 1
  • 20
  • 30