简体   繁体   English

JavaScript 对象中的 init function 有什么特别之处吗?

[英]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:在很多代码中,很常见的是会声明一个init function,如下所示:

var someObject = {

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

Are there anything particularly special about the init function that I should know?我应该知道关于 init function 有什么特别之处吗?

For some frameworks perhaps (though prototype and backbone use initialize instead), but there is nothing special about the init functions in plain old javascript也许对于某些框架(尽管prototypebackbone使用initialize代替),但是在普通的旧 javascript 中的init函数并没有什么特别之处

Executive summary: Like others say - init property is not magic in Javascript.执行摘要:就像其他人说的 - Javascript 中的init属性不是魔法。

Longer story: Javascript objects are merely key->value storages.更长的故事:Javascript 对象只是键->值存储。 If you instantiate an object yourself then it's almost empty - it only inherits some properties from its constructor's prototype.如果您自己实例化 object,那么它几乎是空的——它只从其构造函数的原型中继承了一些属性。 This is a sample dump from Chrome inspector:这是来自 Chrome 检查器的示例转储:

> 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. -- 如您所见,列表中没有init The closest to init would be constructor property, which you can read about eg here .init最接近的是constructor属性,您可以在此处了解相关信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM