0

I am having trouble passing arguments through a new object when using an initialiser function. Consider my following examples that I want to be able to create an object that returns an array. Object Ex1 does this fine:

Ex1 = function() {

    myVar = [];
    myVar = Array.apply( myVar, arguments );
    return myVar;

};

ex1 = new Ex1( 'red', 'green', 'blue' );
console.log( ex1);
/* ["red", "green", "blue"] */

However, I want to us an initialiser to keep my code clean. Object Ex2 shows my unexpected result:

Ex2 = function() {

    init = function() {
        myVar = [];
        myVar = Array.apply( myVar, arguments );
        return myVar;
    };

    return init( arguments );

};

ex2 = new Ex2( 'red', 'green', 'blue' );
console.log( ex2 );
/* [[object Arguments] {
   0: "red",
   1: "green",
   2: "blue"
   }] */

As you can see from the log the result is not a clean array.

How do I return an array when creating a new object when using an initialiser function and passing arguments to it?

2
  • You need to learn to use local variables… Commented Oct 13, 2013 at 15:48
  • A very helpful comment... Commented Oct 13, 2013 at 19:53

1 Answer 1

1

This problem is not hard to understand. In a function, arguments is an array-like object which contains all the arguments passed in. In your second example, you passed an array as argument to init function, so arguments in init function is a 2D array.

Ex2 = function() {   
    init = function() {
        myVar = [];
        myVar = Array.apply( myVar, arguments );//arguments: [["red", "green", "blue"]]
        return myVar;
    };

    return init( arguments );//arguments: ["red", "green", "blue"]  
};

You could use a parameter for example:

Ex2 = function() {
    var init = function(argu) {
        return Array.apply( 0, argu );//argu: ["red", "green", "blue"]
    };
    return init( arguments );
};
ex2 = new Ex2( 'red', 'green', 'blue' );
console.log( ex2 );//["red", "green", "blue"]

Another thing is declaring a variable without var will put it in global scope.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah I see now. By passing the arguments object as an argument it is getting wrapped within another arguments object. Thanks... Your post and a good nights sleep has helped me understand. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.