質問

I ran across the following Javascript code.

var Zoo = {
 animals: [],

 init: function (animal_list) {
   for (i = 0; i < animal_list.length; i++) {
     this.animals.push(animal_list[i]);
   }
}

It looks like the init key maps to an executable function. That function takes in an animal list each item in the list into an animal array.

If I were in my native tongue Ruby, I would do something like this:

class Zoo
    def initialize animal_list
       @animals = animal_list  #animal_list is an array
    end
end

So is init the javascript equivalent of an initialize function? In ruby, I can call

my_ruby_zoo = Zoo.new ["lions", "tigers", "bears"]

In javascript, does the init function map to

var my_javascript_zoo = Zoo.new( ["lions", "tigers", "bears"]); 
役に立ちましたか?

解決

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();

他のヒント

If you want to make your Zoo class a constructor it should be a function instead of an object literal:

var Zoo = function(animal_list) {
 this.animals = [];

 for (i = 0; i < animal_list.length; i++) {
   this.animals.push(animal_list[i]);
 }
}

var myZoo = new Zoo(["lions", "tigers", "bears"]);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top