Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I am wondering if the code beneath considered as the proper way to achieve the topics stated in the title of the post.

I wonder is the best practice for achieving it?

var Obj = function() {
    if (arguments.length) {
        //do something
        for (var i in arguments) //iterate over the arguments
            alert(arguments[i]);
    }
};

Obj.prototype.foo = function() {
    alert("foo");
    return this;
};

Obj.prototype.bar = function() {
    alert("bar");
    return this;
};

Obj.spam = function() {
    alert("spam");
};

//varargs constructor
var varargs = ["arg1", "arg2"];
new Obj();
new Obj(varargs);
new Obj("a", "b", 1, 2.5);

//method chaining
new Obj().foo().bar();

//static method
Obj.spam();
share|improve this question

migrated from stackoverflow.com Oct 21 '12 at 22:58

This question came from our site for professional and enthusiast programmers.

    
Why not just use arguments from within the function? –  Jay Oct 20 '12 at 9:30

1 Answer 1

Answer: Yes, yes, and yes.

Honestly, I'm wondering how else you'd achieve it. The arguments object exists to let you access whatever was passed; return this is really the only way to allow chaining; and the "static" method is technically just an object property, and that's the way you define those.

Only things I'd add is that you can easily convert the arguments object - which is "array-like" but not actually an array - to a real array by saying [].slice.call(arguments, 0);. Useful for looping, slicing, etc.. And you should always use braces/curly brackets - even if the "block" is just 1 line - just good code hygiene. Oh, and when in doubt, use hasOwnProperty() in a for...in loops.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.