1

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

// 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"));
4

1 回答 1

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; 
 }());
于 2012-11-16T09:58:22.060 回答