user2971752
user2971752

Reputation: 107

Why NaN inside function?

This is my code:

        var Paint = (function(cells) {

        var step = $('.workplace').width()/cells;
        var plants = [];

        var cell = function(cells) {
            for (var i=1; i < cells; i++) {
            $('.workplace').append("<div class='line-vertical' style='left: " + step * i + "px;' >")
            $('.workplace').append("<div class='line-horizontal' style='top: " + step *i + "px;'>");
            }
    return {
      cell:cell
    }
        };)()

Paint.cell(10);

In this code step = NaN, why and how can I fixed it?

Upvotes: 0

Views: 62

Answers (2)

IMSoP
IMSoP

Reputation: 97688

You are defining a function which takes a single parameter (function(cells)), but you are then immediately executing it without any parameters; if we take the first and last lines of your code, you get this:

var Paint = (function(cells) {
     // code referencing cells here
};)()

This assigns Paint not to the function, but to the result of executing that function, just as if you'd written this:

function something(cells) {
     // code referencing cells here
};
var Paint = something()

Since you are executing the function with no parameters, cells will be undefined, so the line which is erroring:

var step = $('.workplace').width()/cells;

is dividing a number by an undefined variable.

Upvotes: 0

Fenton
Fenton

Reputation: 250842

Here is a short example of your code that highlights the problem...

var Paint = (function(cells) {
    alert(cells);
})();

It would work if you defined the cells argument...

var Paint = (function(cells) {
    alert(cells);
})(5);

Although I suspect you want to do that inside of the cell function, so move your width calculation inside there.

Upvotes: 1

Related Questions