将调用者的引用添加到闭包构造函数中

时间:2012-11-16 09:11:56

标签: javascript closures prototype

好的,我在一个闭包中创建一个构造函数对象(将其隐藏在可能与之冲突的其他脚本中)以用于另一个函数(这将在一瞬间变得清晰)。有没有办法将调用函数的引用添加到闭合构造函数中:

// this can be located anywhere within a script
(function() {
    function SomeConstructor(param) { this.param = param; }
    SomeConstructor.prototype.doSomething = function(a) { this.param = a; return this; }
    SomeConstructor.prototype.getParam = function() { return this.param }
    // SomeConstructor.prototype.someFunct = ???

    return function someFunct(param) {
        if (param instanceof SomeConstructor) {
            return param;
        }
        else if (param) {
            return new SomeConstructor(param);
        }
    }
}());

我需要引用的原因是因为我可以在someFunct和它构造的对象之间进行链接:

someFunct("A").doSomething("a").someFunct("B").doSomething("a").getParam();



请注意我需要保留instanceof支票,以便按照规定执行以下功能:

// 1: The inner call creates a new instance of SomeConstructor
// 2: The 2nd(wrapping) call returns the inner calls instance
//        instead of creating a new isntance
var a = someFunct(someFunct("b"));

1 个答案:

答案 0 :(得分:1)

首先将函数分配给原型的属性,然后返回此属性:

(function() {
  function SomeConstructor(param) { this.param = param; }
  SomeConstructor.prototype.doSomething = function(a) { this.param = a; return this; }
  SomeConstructor.prototype.getParam = function() { return this.param }
  SomeConstructor.prototype.someFunct = function someFunct(param) {
     if (param) {
          return new SomeConstructor(param);
     }
   }

   return SomeConstructor.prototype.someFunct; 
 }());