简体   繁体   English

Javascript运行对象和所有这些方法

[英]Javascript run object and all this methods

I've created the following jQuery OOP code 我创建了以下jQuery OOP代码

(function ($) {

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


})(jQuery);

I don't want to use init() and call some methods on document ready. 我不想使用init()并在文档就绪上调用一些方法。 Is there any way to execute/run the object in literal notation?? 有没有办法以文字符号执行/运行对象? I used var example = new Object(); 我用var example = new Object(); but I'm getting error, I just need all the methods associated to the objects to be running on ready. 但我收到错误,我只需要准备好运行对象的所有方法。

This will do it :) 这样做:)

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

If you want to use new such as 如果你想使用new

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

You could do something like this 你可以这样做

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

Perhaps this is what you're looking for? 也许这就是你要找的东西?

(function ($) {

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

})(jQuery);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM