简体   繁体   English

如何使用'new'从另一个函数/对象中的函数创建对象

[英]How do I create an object from a function within another function/object using 'new'

I am trying to create an api that extends some functionality of Tizen. 我正在尝试创建一个扩展Tizen功能的api。

Tizen has a way of creating objects such as: 'new tizen.ContactName(...)' and 'addressbook = tizen.contact.getDefaultAddressBook();'. Tizen有一种创建对象的方法,例如:'new tizen.ContactName(...)'和'addressbook = tizen.contact.getDefaultAddressBook();'。

This seems to be a nice way to group together methods and objects when there are a lot of them. 当有很多方法和对象时,这似乎是一种很好的方法。

So, for example I want to extend the contact handling: 所以,例如我想扩展联系处理:

(An external js-file) (外部js文件)

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

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

    this.otherMethod(){...}
}

etc. 等等

I can call this by using: var contactManager = new ContactManager(); 我可以通过使用以下来调用它: var contactManager = new ContactManager(); and it works fine. 它工作正常。 Now I want to access by include it in another object(?) so that it looks like: var contactManager = new myTizen.ContactManager() . 现在我想通过将它包含在另一个对象(?)中来访问它,使它看起来像: var contactManager = new myTizen.ContactManager()

I tried: 我试过了:

function myTizen(){

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

This doesn't work. 这不起作用。 Why? 为什么? How should I build my "API"? 我该如何构建我的“API”?

I see it like this 我觉得这样

define some object myTizen 定义一些对象myTizen

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

Here's what you want: 这是你想要的:

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;

The main difference between option 1 and option 2 is that in the second method, your "subclass" remains in scope and can be used independently of your myTizen class, in the first method once the constructor goes out of scope, you can only access it through myTizen.ContactManager . 选项1和选项2之间的主要区别在于,在第二种方法中,您的“子类”仍然在范围内并且可以独立于myTizen类使用,在第一种方法中,一旦构造函数超出范围,您只能访问它通过myTizen.ContactManager

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

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