javascript JavaScriptprototype.init 的疯狂
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8577541/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript prototype.init craziness
提问by Moonwalker
Could someone please explain the significance of prototype.init function in JavaScript and when it is called during object instantiation?
有人可以解释一下prototype.init函数在JavaScript中的意义以及在对象实例化过程中何时调用它吗?
Why would you want to overwrite it with an empty function?
为什么要用空函数覆盖它?
I am reading the JavaScript for Web book and am stuck on the this for the past few hours...what is piece of code supposed to achieve?
我正在阅读 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;
...
}
This is just too much magic for me...:)
这对我来说太神奇了...:)
回答by Alex Turpin
I'm not sure what you don't understand. init
is simply a method like any other, that happens to be called in the constructor and with the same parameters as the constructor. If it's empty then it's just because the person who wrote it didn't need to put anything in it for now but wanted to lay down the groundworks of his class.
我不确定你不明白什么。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
回答by Raynos
what is piece of code supposed to achieve?
什么是一段代码应该实现?
Confusion.
困惑。
var Class = function() {
// initialization logic
}
// Shortcut to access prototype
Class.fn = klass.prototype;
// Shortcut to access class
Class.fn.constructor = Class;