Search the Community
Showing results for tags 'javascript trick'.
-
I've learned this one from Effective Javascript . Basically it says that instead passing a long list of arguments to function just pass an options (opts) object. This way even if you'll add additional args in the future everything will be kept neat and clean and the user (you or others) won't have to guess what each arg is intended for. This may seem like an overkill for simple functions but imagine functions that take 5, 10 or even more arguments. You could say that it is bad practice but you'll have a function like this in your program one time or another. Or you could use named arguments but they do have to be in a specific order (last in args list). And using the opts object has it's advantages - you can pass args in whatever order you like and omit as many as you like and the function will still probably work - because you'll have implemented an arg check section that sets them to defaults - you'll probably do it anyway with normal arguments. So hands down this is the trick that is making my code waaayyy more usable, clean and easy to use. Let's see it in action - I'll be using examples from the book: Here's a function without an option object with lots of args (USAGE): var alert = new Alert(100, 75, 300, 200, "Error", message, "blue", "white", "black", "error", true); Here's the same function with an option object (USAGE) - note that you can input them in any order you want or miss them completely: var alert = new Alert({ x: 100, y: 75, width: 300, height: 200, title: "Error", message: message, titleColor: "blue", bgColor: "white", textColor: "black", icon: "error", modal: true }); And here's the implementation of the function with the option object: function Alert(parent, message, opts) { opts = opts || {}; // default to an empty options object this.width = opts.width === undefined ? 320 : opts.width; this.height = opts.height === undefined ? 240 : opts.height; this.x = opts.x === undefined ? (parent.width / 2) - (this.width / 2) : opts.x; this.y = opts.y === undefined ? (parent.height / 2) - (this.height / 2) : opts.y; this.title = opts.title || "Alert"; this.titleColor = opts.titleColor || "gray"; this.bgColor = opts.bgColor || "white"; this.textColor = opts.textColor || "black"; this.icon = opts.icon || "info"; this.modal = !!opts.modal; this.message = message; } It may be a little bit more work to do for the arg check but you're going to use it a lot more times than write it. And it forces you to do arg check and provide defaults (which is a very,very good thing). And it's more readable and "writeable" IMO.