2011-04-13 66 views
0

我想创建一个JavaScript的应用程序,它是这样工作的:如何在初始化后扩展JavaScript对象/函数以公开API方法?

  • 具有这样的功能/命名空间称为bm
  • 在开始时,bm只是一个函数,它具有一个名为setup的方法,因此有两件事是可能的:调用bm()或定义一些调用bm.setup(settings)的设置变量。
  • 要使用该库并公开API bm必须先通过调用函数bm(url, options)来初始化。如果成功初始化,该API予以曝光,从而bm现在有更多的方法,如bm.method1bm.method2 ...

我不知道究竟怎么可能,所以我想听到的任何想法,实例或建议。提前致谢。

回答

3

功能是一流的对象,所以你可以给它们添加方法。然后你的主实例创建功能,只需要检查并确保其称为一个实例:

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

也许像...

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); 
} 
0

我这里看不到任何问题。您可能需要一个回调函数添加到BM(),当API初始化被称为像这样:

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

您可以添加功能,BM像一个普通的对象:

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