我遇到了以下 Javascript 代码。
var Zoo = {
animals: [],
init: function (animal_list) {
for (i = 0; i < animal_list.length; i++) {
this.animals.push(animal_list[i]);
}
}
看起来 init 键映射到一个可执行函数。该函数将动物列表中的每个项目接收到动物数组中。
如果我用我的母语 Ruby,我会做这样的事情:
class Zoo
def initialize animal_list
@animals = animal_list #animal_list is an array
end
end
那么 init 相当于 JavaScript 中的初始化函数吗?在 ruby 中,我可以调用
my_ruby_zoo = Zoo.new ["lions", "tigers", "bears"]
在 javascript 中,init 函数是否映射到
var my_javascript_zoo = Zoo.new( ["lions", "tigers", "bears"]);
最佳答案
Is init a special reserved keyword for Javascript Object Literals?
不,一点也不。 JavaScript 中没有用于初始化的预命名函数。通常,如果您需要 JavaScript 中的对象“类”,则可以使用带有 new
关键字的构造函数:
function Person(first, last) {
this.first = first;
this.last = last;
}
// Usage:
var chuck = new Person("Charles", "Foreman");
然后,您可以添加通过 new Person
创建的所有实例都可以使用的函数,方法是将它们作为属性添加到分配给通过 new Person
创建的对象的原型(prototype)(该原型(prototype)取自 Person.prototype
属性):
Person.prototype.getFullName = function() {
return this.first + " " + this.last;
};
因为这有点啰嗦,而且处理继承层次结构比其他语言更费力(ES6 中已经修复了这一点),所以有很多库提供了帮助函数来连接事物你。 (我的名为 Lineage
,还有 Resig 的 Really Simple Inheritance 、PrototypeJS 的 Class
等)其中一些帮助脚本可能会赋予某些函数名称特殊含义。例如,在 Lineage
和 PrototypeJS 的 Class
中,一个名为 initialize
的函数是特殊的。 (我见过一些 ctor
的特殊之处。)
但不在 JavaScript 本身内。
您的动物园
可能如下所示:
function Zoo(animal_list) {
this.animals = animal_list.slice(0); // Copy the array
}
如果您想添加所有 Zoo
实例上可用的函数,通常您会将它们添加到 new Zoo
分配的原型(prototype)中:
Zoo.prototype.showAll = function() {
this.animals.forEach(function(animal) {
console.log(animal);
});
};
// Usage:
var z = new Zoo(['Tortoise', 'Emu', 'Lion']);
z.showAll();
关于javascript - init 是 Javascript 对象文字的特殊保留关键字吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21683304/