22

我意识到您可以像这样自动运行对象中的属性:

var obj = {

    init:(function(){ alert('loaded');})();

}

我正在尝试将此方法用作对象的初始化程序。我遇到的问题是将 'obj' 的引用传递给 init 属性。我怀疑它会产生错误,因为 obj 尚未完全内置在浏览器中。我正在尝试执行以下操作,但没有成功。如果有办法做到这一点,我很想知道如何。

var obj = {
    prop:function(){ alert('This just ran.'); },
    init:(function(){ obj.prop(); })();
}
4

9 回答 9

23

如果你想创建多个相似对象的实例,你应该使用普通的旧构造函数(记住将共享属性放在原型中!)。

如果要创建单个对象,请考虑使用匿名构造函数。您的示例将显示为:

var obj = new (function() {
    this.prop = function() {
        alert('This just ran.');
    }

    // init code goes here:
    this.prop();
});

这比对象文字有一个额外的好处:构造函数可以用作“私有”变量的闭包。

不要过度使用对象字面量:它们可能会使简单的事情变得简单,但复杂的事情会变得过于复杂。

于 2009-03-08T14:05:52.340 回答
5

这是不可能的:在整个块被解释之前,obj 不存在。

于 2009-03-08T12:15:33.383 回答
4

一个简单的替代方案:

var obj = {

  init: function(){ 
    alert('loaded');
  }

}.init();
于 2014-02-12T22:24:36.583 回答
3

你为什么不使用构造器模型(实际上,我不知道它的正确名称):

function Obj() {
    // Initialising code goes here:
    alert( 'Loaded!' );

    // ...

    // Private properties/methods:
    var message = 'hello',
        sayHello = function() {
            alert(message);
        };

    // Public properties/methods:
    this.prop = function() {
        sayHello();
    };

    // Encapsulation:
    this.setMessage = function(newMessage) {
        message = newMessage;
    };
}

用法:

var instance = new Obj();
instance.setMessage('Boo');
instance.prop();
于 2009-03-08T12:46:06.667 回答
2

是的,obj 似乎直到后来才在本地存在。这对我有用setTimeout。在 IE8、FF5、Chrome 12、Opera v11.5 上测试正常。虽然不确定 50 毫秒,但我想这已经足够了。

var obj = {
    prop: function() { alert('This just ran.') },
    init: ( function(){ setTimeout(function(){obj.prop()},50) } )()
}
于 2011-07-04T13:30:29.843 回答
1

以类 jQuery 风格初始化

(function() {

var $ = function(){
  return new $.fn.init();
};

$.fn = $.prototype = {
  init: function(){ 
    this.prop(); 
  },
  i: 0,
  prop: function(){ 
    alert('This just ran. Count: ' + (++this.i)); 
    return this;
  }
};

$.fn.init.prototype = $.fn;

$().prop().prop();

})();

jsbin.com

于 2013-09-28T15:02:03.977 回答
1

这是对 user1575313 提交的示例的更新。

原始代码有效,但它限制了设置后对象的使用。通过在 init 方法中返回对象引用,它允许在对象之外使用对象。

链接到 jsFiddle。jsFiddle

var obj = {

init: function()
{ 
    alert('loaded'); 

    this.consoleLog(); 

    /* we want to return this to keep object 
    usable after auto init */ 
    return this;
}, 

consoleLog: function() 
{
    console.log(1); 
}

}.init(); 

/* the obj should now be usable outside the auto init */ 
obj.consoleLog();
于 2014-12-31T17:34:39.013 回答
0

我想你想尝试这样的事情:

var obj = {
    prop: function() { alert('This just ran.'); },
    init: function() { obj.prop(); }
}

对象文字需要逗号分隔的成员,不带分号。

于 2009-03-08T12:14:18.833 回答
-1

如果将“this”传递给init函数,它会起作用吗?

类似的东西:(未经测试)

var obj = {
    prop:function(){ alert('This just ran.'); },
    init:(function(o){ o.prop(); })(this);
}
于 2009-03-08T12:14:12.187 回答