Daniel Chen
Daniel Chen

Reputation: 103

How to "new" a returned function in Javascript

I am trying to simulate a namespace feature in Javascript.

var com                   = {};
com.domain                = {};
com.domain.system         = {};
com.domain.net            = {};
com.domain.net.ip         = {};
com.domain.net.ip.tcp     = {};
com.domain.net.ip.udp     = {};
com.domain.net.ip.ssl     = {};
com.domain.util           = {};
com.domain.util.timer     = {};
com.domain.plugins        = {};
com.domain.session        = {};
com.domain.io             = {};
com.domain.algorithm      = {};
com.domain.debug          = {};

This is the namespaces declaration. Later I will add functions to these namespaces.

This is my selector function:

For a convenient way to use namespaces, I add a function named $. This function will walk all namespaces in com. If the selected name exists, return the object.

function $ (selector) {
  function digger (namespace, selector) {
    for (var prop in namespace) {
      if (typeof namespace[prop] == "array" || typeof namespace[prop] == "object") {
        if (prop == selector) {
          return namespace[prop];
        }
        var dig = digger(namespace[prop], selector);
        if (dig != null) {
          return dig;
        }
      } else {
        if (prop == selector) {
          return namespace[prop];
        }
      }
    }
  }
  return digger (com, selector);
}

After that, I add a timer to namespace com.doamin.util.

com.domain.util.timer = function () {
    this._handle = new InnerObj.SystemTimer(io);
    return this;
};

com.domain.util.timer.prototype.expiresFromNow = function (seconds, cbHandler) { 
    this._handle.ExpiresFromNow (seconds, cbHandler);
};

com.domain.util.timer.prototype.wait = function (seconds, cbHandler) { 
    this._handle.Wait (seconds, cbHandler);
};

com.domain.util.timer.prototype.expiresAt = function (seconds, cbHandler) { 
    this._handle.Wait (seconds, cbHandler);
};

com.domain.util.timer.prototype.cancel = function () {
    this._handle.Cancel ();    
};

Usage:

 1. var timer = new com.domain.util.timer ();            OK
    timer.expiresAt (1, {});                             OK
 2. var func = $("timer");                               OK 
    var timer =  new func ();                            OK 
    timer.expiresAt (1, {});                             OK

But but but but but

var timer = new $("timer") ();                           NG

Can anyone tell me why the last new function is not working?

Upvotes: 0

Views: 84

Answers (1)

mpm
mpm

Reputation: 20155

Try var timer = new ($("timer"))();.

Your question is not clear but I guess since $("timer") returns a function, you want a new instance of the result of $("timer") and not a new instance of $().

Upvotes: 1

Related Questions