【问题标题】:How to extend a JavaScript object/function to expose API methods after initialization?如何在初始化后扩展 JavaScript 对象/函数以公开 API 方法?
【发布时间】:2011-04-13 18:18:47
【问题描述】:

我想创建一个像这样工作的 javascript 应用程序:

  • 有一个名为 bm 的函数/命名空间。
  • 一开始 bm 只是一个函数,它有一个名为 setup 的方法,所以有两种可能:调用 bm() 或定义一些设置变量调用 bm.setup(settings)
  • 要使用库并公开 API bm,必须首先通过调用函数来初始化:bm(url, options)。如果初始化成功,API 应该被公开,所以 bm 现在有额外的方法,如 bm.method1bm.method2、...

我不知道这到底是怎么可能的,所以我想听听任何想法、示例或建议。提前致谢。

【问题讨论】:

    标签: javascript function object


    【解决方案1】:

    好在函数是一流的对象,因此您可以向它们添加方法。然后你的主实例创建函数只需要检查并确保它作为一个实例被调用:

    var bm = function(settings) {
        if (!(this instanceof bm)) {
            return new bm(settings);
        }
    
        // Now we are sure we are working with
        // a new instance. Let's do stuff here 
        // to our new object.
    }
    
    bm.setup = function(settings) {
        return new bm(settings);
    }
    

    这可以称为以下任何一种方式:

    var myObj = new bm();
    
    var myObj = new bm(settings);
    
    var myObj = bm();
    
    var myObj = bm(settings);
    
    var myObj = bm.setup(settings);
    

    【讨论】:

      【解决方案2】:

      也许是……

      function bp ( url, options ) {
          if ( !url || !options)
              return 'You fail mister';
      
          //declare stuff here:
          this.aMethod = function() {...};
          this.anAttribute = true;
      
          return this;
      }
      bp.setup = function( settings ) {
          return new bp( predefinedURL, settings);
      }
      

      【讨论】:

        【解决方案3】:

        我认为这里没有任何问题。您可能希望在 bm() 中添加一个回调函数,该函数在 API 初始化时调用,如下所示:

        onAPIInitialized = function() { use the API };
        bm(url, options, onAPIInitialized);
        

        你可以像普通对象一样向 bm 添加函数:

        bm.method1 = function(...) {}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-01
          相关资源
          最近更新 更多