开发者

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

In a lot of cod开发者_JAVA百科e, 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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜