【问题标题】:Javascript run object and all this methodsJavascript 运行对象和所有这些方法
【发布时间】:2013-06-27 02:34:30
【问题描述】:

我创建了以下 jQuery OOP 代码

(function ($) {

    example = {
      method1 : function()  {},
      method2   : function()  {}        
    };


})(jQuery);

我不想使用init() 并在准备好文档时调用一些方法。有没有办法以文字表示法执行/运行对象?我使用了var example = new Object();,但出现错误,我只需要与对象关联的所有方法都准备好运行。

【问题讨论】:

  • 您打算稍后在代码中使用示例对象吗?
  • 嗨,不是真的......这只是流程

标签: javascript oop object


【解决方案1】:

这样就可以了:)

(function ($) {

    // define some methods
    var example = {
      method1: function() { console.log(1); },
      method2: function() { console.log(2); }        
    };

    // run all methods in example
    for (var m in example) {
      if (example.hasOwnProperty(m) && typeof example[m] === "function") {
        example[m]();
      }
    }

    // => 1
    // => 2

})(jQuery);

如果你想使用new比如

var example = new Example();
// => "A"
// => "B"

你可以这样做

(function($) {

  var Example = function() {
    this.initializeA();
    this.initializeB();  
  };

  Example.prototype.initializeA = function() {
    console.log('A');
  }

  Example.prototype.initializeB = function() {
    console.log('B');
  };

  // init
  new Example();
  // => "A"
  // => "B"

})(jQuery);

【讨论】:

  • @AdamRackis,对此感到抱歉。我正在编辑答案以添加更多详细信息,它覆盖了您的更改。不过,您的更改看起来不错,谢谢。
  • 嗨,谢谢它的工作我也知道这个逻辑,但我认为它有任何其他更简单的方法来初始化对象的方法而没有任何重载。例如,如果对象包含 100 多个奇怪的方法,我担心执行时间。感谢您的帮助
【解决方案2】:

也许这就是你要找的东西?

(function ($) {

    example = (function() {alert("some code")})();
    //or
    (function() {alert("some other code")})();
    //or
    alert("even more code");

})(jQuery);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 1970-01-01
    • 2012-11-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多