Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript prototype.init craziness

Tags:

javascript

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

like image 721
Moonwalker Avatar asked Dec 20 '11 15:12

Moonwalker


2 Answers

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/

like image 179
Alex Turpin Avatar answered Nov 15 '22 11:11

Alex Turpin


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;
like image 20
Raynos Avatar answered Nov 15 '22 10:11

Raynos