Ph0en1x
Ph0en1x

Reputation: 10067

passing unknown count of parameters to js constructor function

I use some javascript library for drawing charts. It need to pass arrays with coordinates in to chart initializer. But chart initializer function have a signature looks like new function ([arr1], [arr2], [arr3]), but I don't know how much arrays I will pass into that, but it impossible to initialize it another way. How it possible to solve this? Thanks.

UPD: function called is constructor, so it's not work correctly with apply. Problem is how to pass data, but not how to get the count of passed data

Upvotes: 1

Views: 3686

Answers (4)

Nenad
Nenad

Reputation: 3556

Functions that accept a variable number of arguments are called variadic functions. In JavaScript you can use the arguments object to access the arguments. To invoke the function you can also use .call or .apply

Upvotes: 0

Ph0en1x
Ph0en1x

Reputation: 10067

SOLUTION: It's possible to use apply in constructor, but it needs the following workaround:

function construct(constructor, args) {
    function F() {
        return constructor.apply(this, args);
    }
    F.prototype = constructor.prototype;
    return new F();
}

Upvotes: 5

jfriend00
jfriend00

Reputation: 707158

You can use the built in variable called arguments which is an array-like object of the arguments passed to the function and arguments.length to determine how many arguments were passed. See this MDN reference for more info.

function myFunc() {
    for (var i = 0; i < arguments.length; i++) {
        // you can process arguments[i] here
    }
}

If you're trying to pass a variable number of arguments, you can use .apply(). You construct an array of the arguments and pass that as the second argument to apply. The first argument is what you want the this pointer to be set to. Here's the MDN reference for .apply().

var myArgs = [arr1, arr2, arr3];
myFunc.apply(window, myArgs);

Upvotes: 3

Some Guy
Some Guy

Reputation: 16190

You want to use the arguments object. It's basically an array-like object with all your arguments in it. You can use it like this:

function yourFunction() {
    for (var i = 0, len = arguments.length; i < len; i++) {
        console.log(arguments[i]); //That's the argument you passed in.
    }
}

Demo

Upvotes: 0

Related Questions