Javascript - 对象初始化程序? [英] Javascript - object initializer?
问题描述
我已经意识到你可以像这样自动运行一个对象中的属性:
I've realized you can have a property in an object run automatically like this:
var obj = {
init:(function(){ alert('loaded');})();
}
我正在尝试将此方法用作初始值设定项物体。我遇到的问题是将对'obj'的引用传递给init属性。我怀疑它会产生错误,因为obj还没有在浏览器中完全构建。我正在尝试执行以下操作,但未成功。如果有办法做到这一点,我很想知道如何。
I'm trying to use this method as an initializer for the object. The problem I'm running into is passing a reference to 'obj' to the init property. I suspect it generates errors because the obj hasn't been completely built in browser yet. I'm trying to do the following, but unsuccessfully. If there's a way to do this, I'd love to know how.
var obj = {
prop:function(){ alert('This just ran.'); },
init:(function(){ obj.prop(); })();
}
推荐答案
如果你想创建多个类似对象的实例,你应该使用普通的老构造函数(记得把共享属性放在原型中!)。
If you want to create multiple instances of similar objects, you should use plain old constructor functions (remember to put shared properties in the prototype!).
如果你想创建一个对象,考虑使用一个匿名的构造函数。你的例子如下:
If you want to create a single object, consider using an anonymous constructor. Your example would read:
var obj = new (function() {
this.prop = function() {
alert('This just ran.');
}
// init code goes here:
this.prop();
});
这比对象文字有额外的好处:构造函数可以用作'私有的闭包'变量。
This has an additional benefit over object literals: the constructor function can be used as a closure over 'private' variables.
不要过度使用对象文字:它们可能使简单的事情变得简单,但复杂的事情会变得过于复杂。
Don't overuse object literals: they may make simple things simple, but complex things will get overly complicated.
这篇关于Javascript - 对象初始化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!