Sal Rahman
Sal Rahman

Reputation: 4755

Is there anything special about the init function in JavaScript objects?

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?

Upvotes: 7

Views: 2882

Answers (2)

Tomasz Zieliński
Tomasz Zieliński

Reputation: 16377

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.

Upvotes: 6

Pablo Fernandez
Pablo Fernandez

Reputation: 105258

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

Upvotes: 9

Related Questions