Could someone please explain the significance of prototype.init function in JavaScript and when it is called during object instantiation?
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?
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...:)
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.
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
http://jsfiddle.net/Hmgch/
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With