JavaScript prototype.init疯狂

Moo*_*ker 12 javascript

有人可以在JavaScript中解释prototype.init函数的重要性以及在对象实例化期间调用它的时间吗?

你为什么要用空函数覆盖它?

我正在阅读用于Web书的JavaScript,并且在过去的几个小时里我一直坚持这个...那段代码应该实现什么?

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;

...
}
Run Code Online (Sandbox Code Playgroud)

这对我来说太神奇了...... :)

Ale*_*pin 13

我不确定你不懂什么.init它只是一个像任何其他方法一样的方法,恰好在构造函数中调用,并且具有与构造函数相同的参数.如果它是空的,那只是因为编写它的人现在不需要放任何东西但是想要放下他班级的基础.

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
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/Hmgch/