2
\$\begingroup\$

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();
asked Oct 19, 2012 at 15:46
\$\endgroup\$
1
  • \$\begingroup\$ Why not just use arguments from within the function? \$\endgroup\$ Commented Oct 20, 2012 at 9:30

1 Answer 1

2
\$\begingroup\$

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.

answered Oct 22, 2012 at 1:17
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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