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

In lots of code, you can often declare an init function, for example:

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

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

+7
source share
2 answers

It is possible for some frameworks (although prototype and backbone use initialize instead), but there is nothing special about init functions in plain old javascript

+9
source

Summary: As others say, the init property is not magic in Javascript.

A longer story. Javascript objects are just key-> value storerooms. If you create an instance of the object yourself, it is almost empty - it inherits some properties only from its prototype constructor. This is a sample dump from a 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 in the list. The closest to init will be the constructor property, which you can read about, for example. here .

+6
source

All Articles