What’s the proper way to create an object (with its “namespaces” and such)?
1
//Company object
var Microsoft = {};
//Create an employee
Microsoft.employee = function(name) {
this.name = name;
}
or
2
//Company object
Apple = {
employee: function(name) {
this.name = name;
}
}
OR another way? Shoot.
Read something about prototypes and such. What’s the proper way to do it; benefits and downsides?
First off, you forgot the
varforApple. But otherwise these are basically the same thing.Secondly, in my examples I’m not going to use the attribute
namesince, when dealing with functions, thenameis an empty string by default. At least in Node.js and Chrome. So I’ll useempNameinstead.In the
Microsoftexample you are making an empty object and then adding an attribute to it after the fact.In the
Appleexample you are making an object with the attribute right away.It’s really just what makes the most sense to you, and which you prefer. Since they are, more or less, equivalent.
Now, this has nothing to do with prototypes. Here’s an example of what you did:
And here’s how you would do this with an instance (using the
newoperator, and theprototype)So
prototypeis used to add attributes to new instances of an object (using ‘object’ loosely). Note that to accessemployeeinApple, on this second example, you would have to do something likeHope that helps.
EDIT: Also, don’t prototype objects (e.g.
{}orObject). It’s not safe to do this. Since, essentially, every variable in JavaScript is an object, then any prototypes you add to them will be available on all variables. So if you didObject.prototype.xyz = 12then hadvar obj = { a: 1, b: 2, c: 3}and then triedfor(var key in obj) { console.log(key); }you would result in the following logs:a,b,candxyz… which you wouldn’t want.