0

我正在尝试创建一个扩展 Tizen 某些功能的 api。

Tizen 有一种创建对象的方法,例如:“new tizen.ContactName(...)”和“addressbook = tizen.contact.getDefaultAddressBook();”。

当有很多方法和对象时,这似乎是一种将方法和对象组合在一起的好方法。

因此,例如,我想扩展联系人处理:

(外部 js 文件)

function ContactManager(){ //edited by comment
    var self = this;

    this.add = function(details, posCallback, negCallback){
    //do stuff to add contact

    this.otherMethod(){...}
}

等等

我可以通过使用来调用它:var contactManager = new ContactManager();它工作正常。现在我想通过将它包含在另一个对象(?)中来访问它,它看起来像:var contactManager = new myTizen.ContactManager().

我试过了:

function myTizen(){

this.ContactManager = function(){
    //methods and stuff
    }
}

这行不通。为什么?我应该如何构建我的“API”?

4

2 回答 2

1

我是这样看的

定义一些对象 myTizen

然后设置myTizen.ContactManager = somefunction();

于 2014-03-25T13:03:23.590 回答
1

这就是你想要的:

function myTizen() {
    function whatevername() {
        // methods and stuff
    }
    // you can even extend whatevername's prototype down here

    this.ContactManager = whatevername; // please note the lack of parentheses
}

// here's another way you could do it:
function alternateMyTizen() {
}

function alternatewhatever() {
    // methods and stuff
}
// extend the prototype if you choose

alternateMyTizen.prototype.ContactManager = alternatewhatever;

选项 1 和选项 2 之间的主要区别在于,在第二种方法中,您的“子类”保留在范围内,并且可以独立于您的 myTizen 类使用,在第一种方法中,一旦构造函数超出范围,您就只能访问它通过myTizen.ContactManager.

于 2014-03-25T13:17:32.710 回答