7

In a lot of code, it's very common to see an init function be declared, like so:

var someObject = {

    // What is this for?
    init: function () {
        // Call here.
    }
};

Are there anything particularly special about the init function that I should know?

Swift
  • 13,118
  • 5
  • 56
  • 80
Sal Rahman
  • 4,607
  • 2
  • 30
  • 43

2 Answers2

9

For some frameworks perhaps (though prototype and backbone use initialize instead), but there is nothing special about the init functions in plain old javascript

Pablo Fernandez
  • 103,170
  • 56
  • 192
  • 232
6

Executive summary: Like others say - init property is not magic in Javascript.

Longer story: Javascript objects are merely key->value storages. If you instantiate an object yourself then it's almost empty - it only inherits some properties from its constructor's prototype. This is a sample dump from Chrome inspector:

> obj = {}
Object
+-__proto__: Object
 |-__defineGetter__: function __defineGetter__() { [native code] }
 |-__defineSetter__: function __defineSetter__() { [native code] }
 |-__lookupGetter__: function __lookupGetter__() { [native code] }
 |-__lookupSetter__: function __lookupSetter__() { [native code] }
 |-constructor: function Object() { [native code] }
 |-hasOwnProperty: function hasOwnProperty() { [native code] }
 |-isPrototypeOf: function isPrototypeOf() { [native code] }
 |-propertyIsEnumerable: function propertyIsEnumerable() { [native code] }
 |-toLocaleString: function toLocaleString() { [native code] }
 |-toString: function toString() { [native code] }
 |-valueOf: function valueOf() { [native code] }    > obj = {}

-- as you can see, there is no init on the list. The closest to init would be constructor property, which you can read about e.g. here.

Community
  • 1
  • 1
Tomasz Zieliński
  • 16,136
  • 7
  • 59
  • 83