谁能解释一下 prototype.init 函数在 JavaScript 中的意义以及它在对象实例化过程中何时被调用?
为什么要用空函数覆盖它?
我正在阅读 JavaScript for Web 这本书,并且在过去的几个小时里一直停留在这个问题上......一段代码应该实现什么?
var Class = function(){
var klass = function(){
this.init.apply(this, arguments);
};
klass.prototype.init = function(){};
// Shortcut to access prototype
klass.fn = klass.prototype;
// Shortcut to access class
klass.fn.parent = klass;
...
}
这对我来说太神奇了...:)
最佳答案
我不确定你不明白什么。 init
只是一个与其他任何方法一样的方法,它恰好在构造函数中被调用,并且具有与构造函数相同的参数。如果它是空的,那只是因为编写它的人暂时不需要在其中放入任何东西,而是想为他的类(class)奠定基础。
function Foo(a, b, c) {
this.init.apply(this, arguments); //This simply calls init with the arguments from Foo
}
Foo.prototype.init = function(a, b, c) {
console.log(a, b, c);
}
var f = new Foo(1, 2, 3); //prints 1 2 3
关于JavaScript prototype.init 疯狂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8577541/