我意识到你可以像这样自动运行一个对象:

var obj = {

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

}

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

var obj = {
    prop:function(){ alert('This just ran.'); },
    init:(function(){ obj.prop(); })();
}
有帮助吗?

解决方案

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

如果要创建单个对象,请考虑使用匿名构造函数。你的例子如下:

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

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

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

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

其他提示

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

一个简单的替代方案:

var obj = {

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

}.init();

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

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();

是的,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) } )()
}

这是对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();

以类似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

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

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

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

如果你传递“this”,它会起作用吗?进入init函数?

类似:(未经测试)

var obj = {
    prop:function(){ alert('This just ran.'); },
    init:(function(o){ o.prop(); })(this);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top