在很多代码中,通常会看到init声明一个函数,如下所示:
var someObject = {
// What is this for?
init: function () {
// Call here.
}
};
Run Code Online (Sandbox Code Playgroud)
关于我应该知道的init函数有什么特别之处吗?
执行摘要:像其他人说的那样 - init财产在Javascript中并不神奇.
更长的故事:Javascript对象只是键 - >值存储.如果您自己实例化一个对象,那么它几乎是空的 - 它只从其构造函数的原型继承了一些属性.这是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 = {}
Run Code Online (Sandbox Code Playgroud)
- 正如您所看到的,init列表中没有.最接近的init将是constructor财产,你可以在这里阅读.