Nick Heiner
Nick Heiner

Reputation: 122412

JavaScript: What's wrong with this constructor?

I'm not entirely sure how to implement objects in JS.

Here is a constructor:

function FooList(arg1, arg2, arg3, arg4, arg5, arg6, arg7)
{
    alert("constructing");
    this._arg1 = arg1;
    this._arg2 = arg2;

    this.refresh();
}

I am trying to call it here:

FOO_LIST = new FooList(
    arg1,
    arg2,
    arg3,
    arg4,
    arg5,
    arg6,
    arg7
);

When I have all 7 args, it doesn't work. (No breakpoint in the constructor is hit; and the alert doesn't fire. Also, the method that contains the above code stops executing.)

However, this does result in the alert firing:

FOO_LIST = new FooList();

What am I doing wrong here?

UPDATE Perhaps this is a better way to define a constructor:

FooList = function() { }

rather than

function FooList() { }

However, even using the former approach, it still doesn't work.

UPDATE 2: Looks like Spinon and Russ Cam's comments were correct. One of the args was silently failing when I tried to evaluate it.

Upvotes: 1

Views: 349

Answers (1)

Russ Cam
Russ Cam

Reputation: 125488

You've got a trailing comma after the last arg which is going to cause problems for the JavaScript engines.

In addition, it would be better to use var in front of FOO_LIST, even if it is intentionally a global variable, as this a good habit to get into for all variable declarations and save you from potential problems with global variable overwriting in future.

For cases where you have functions with many parameters like like this, you might want to use the arguments object and index into it to get args 1-7.

Upvotes: 2

Related Questions