Tuesday, May 21, 2024
 Popular · Latest · Hot · Upcoming
165
rated 0 times [  168] [ 3]  / answers: 1 / hits: 18183  / 13 Years ago, tue, december 20, 2011, 12:00:00

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...:)


More From » javascript

 Answers
22

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/


[#88466] Monday, December 19, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loganl

Total Points: 424
Total Questions: 86
Total Answers: 112

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;