What's the benefit to using an object with some stuff in it, like
var cheese = {color: "bleu", smell: "bad", holes: false};
as opposed to storing separate objects for similar data, like
var cheeseColor = "bleu";
var cheeseSmell = "bad";
var cheeseHoles = false;
I know there's higher-level benefits when it comes to prototyping and constructor functions, but for a simple task, does it make a significant difference?
1.) The biggest benefit (in my opinion) is dynamic variable handling.
Let's assume you have an object, but it's loaded through AJAX or the variables aren't made by you. Either way you don't know what's in it.
With normal variables, you're screwed. End.
But with objects, you can ask the user what he wants, and the with the []
operator, you can get that value:
var obj = {
s: 5,
c: "abc",
g: /hello/g
};
function getObjectParam(name) {
return obj[name];
}
Then by calling
getObjectParam("s")/
You get 5
.
This is a very simple use case. I mostly use this feature when I need to store different matrices when I use WebGL for example.
2.) Passing them
Let's say you have a library which needs something configured by the user of the lib. Instead of creating a constructor or a function, which takes in 20 arguments, you can make one which takes in an object, and you use it's values to set everything. This doesn't just make you be able to write a shorter function, but also enables the user to reuse the object if he wants to call the function again.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments