1

次のjQuery OOPコードを作成しました

(function ($) {

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


})(jQuery);

init()ドキュメントの準備ができているときにいくつかのメソッドを使用して呼び出したくありません。オブジェクトをリテラル表記で実行/実行する方法はありますか?? 使用var example = new Object();しましたが、エラーが発生しました。オブジェクトに関連付けられているすべてのメソッドを実行する準備ができている必要があります。

4

2 に答える 2

2

これでできます:)

(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);
于 2013-06-27T02:42:29.750 に答える
1

おそらくこれはあなたが探しているものですか?

(function ($) {

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

})(jQuery);
于 2013-06-27T02:37:53.403 に答える