Is init a special reserved keyword for Javascript Object Literals?
No, not at all. There is no pre-named function for initialization in JavaScript. Typically, if you have need of a "class" of objects in JavaScript, you use a constructor function with the new
keyword:
function Person(first, last) {
this.first = first;
this.last = last;
}
// Usage:
var chuck = new Person("Charles", "Foreman");
You might then add functions that all instances created via new Person
can use, by adding them as properties to the prototype that gets assigned to objects created via new Person
(that prototype is taken from the Person.prototype
property):
Person.prototype.getFullName = function() {
return this.first + " " + this.last;
};
Because this is a bit long-winded and handling inheritance hierarchies is more effort than it is in other languages (something that's being fixed in ES6), there are a lot of libraries out there that provide helper functions to hook things up for you. (Mine is called Lineage
, there's also Resig's Really Simple Inheritance, PrototypeJS's Class
, etc.) Some of these helper scripts may give certain function names special meaning. For instance, in both Lineage
and PrototypeJS's Class
, a function called initialize
is special. (I've seen some where ctor
was special.)
But not within JavaScript itself.
Your Zoo
might look like this:
function Zoo(animal_list) {
this.animals = animal_list.slice(0); // Copy the array
}
If you want to add functions available on all Zoo
instances, typically you'd add them to the prototype assigned by new Zoo
:
Zoo.prototype.showAll = function() {
this.animals.forEach(function(animal) {
console.log(animal);
});
};
// Usage:
var z = new Zoo(['Tortoise', 'Emu', 'Lion']);
z.showAll();