【问题标题】:Add reference of caller to in-closure constructor将调用者的引用添加到封闭构造函数
【发布时间】:2012-11-16 09:11:55
【问题描述】:

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

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

【问题讨论】:

    标签: javascript closures prototype


    【解决方案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; 
     }());
    

    【讨论】:

    • SomeConstructor.prototype.someFunct 中的if (param instanceof SomeConstructor) {...} 将继续按应有的方式处理。我不得不更改代码,因为这不起作用 b/c 每次调用 someFunct 时都会重新创建构造函数,这就是这个问题的来源。
    • 你的意思是this instanceof SomeConstructor 吗?
    • 没有。 someFunct(new someFunct("a")),第一次调用应该创建一个 SomeConstructor 的新实例,使用包装调用,如果它在 someFunct 函数内,if (param instanceof SomeConstructor){...} 的计算结果为 true
    • 这似乎在我尝试时有效。包装调用正确地将其视为SomeConstructor 的实例并返回它而不是创建新对象。它不适合你吗?
    • 问之前我没有测试。以为你可能已经知道了。谢谢,将测试以确保。如果可行,将投票并接受。
    猜你喜欢
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 2023-01-23
    • 2015-03-16
    • 1970-01-01
    • 2018-02-25
    相关资源
    最近更新 更多