【问题标题】:javascript fake instanceofjavascript假instanceof
【发布时间】:2013-03-19 14:10:47
【问题描述】:

我正在尝试使用这种模式创建一个“构造函数”:

function mything() {
    var a, b, c;
    ...
    return {
        publicFunc: function() {
            //access private vars here
        }
    };
}

//usage

mything1 = mything();
mything2 = mything();

问题是,我还想让它通过instanceof 测试:

assert(mything1 instanceof mything === true);

有没有办法做到这一点?使用常规构造函数将不起作用,因为原型函数无法访问私有变量。

【问题讨论】:

  • 为了让instanceof返回true,构造函数的prototype必须在实例的原型链中。

标签: javascript oop constructor


【解决方案1】:

您需要使用稍微不同的设计模式来拥有私有变量并将其作为mything 的实例:

function mything() {
    var a, b, c;
    ...
    this.publicFunc = function() {
            //access private vars here
        }
    };
}

//usage

var mything1 = new mything();
mything1.publicFunc();
var mything2 = new mything();

【讨论】:

    【解决方案2】:

    这在技术上是可行的,但你可以更优雅地解决你的问题(解释如下):

    function mything() {
      var a, b, c;
    
      function PrivateConstructor() {
        this.publicFunc = function() {}
      }
    
      // this is the magic that makes it happen:
      PrivateConstructor.prototype = mything.prototype; 
    
      return new PrivateConstructor();
    
    }
    
    mything1 = mything();
    assert(mything1 instanceof mything); // passes
    

    或者,使用 EcmaScript 5 功能:

    function mything() {
      var a, b, c;
    
      var object = Object.create(mything.prototype);
      object.publicFunc = function() {}
    
      return object;
    }
    
    mything1 = mything();
    assert(mything1 instanceof mything); // passes
    

    说明

    如果右侧操作数是一个函数,instanceof 运算符将返回 true,并且该函数的 prototype 属性中存储的对象包含在左侧操作数的原型链中。

    第一个示例将mything.prototype 重用为另一个临时函数的“原型”属性,该函数仅用于生成一个对象(在其原型链中带有mything.prototype)。第二个示例通过直接从mything.prototype 继承Object.create() 来创建这样的对象。

    两个对象都继承自mything.prototype,因此将通过object instanceof mything 测试。

    话虽如此,jfriend00 提出的模式开销更少,更易于阅读,同时提供了您想要的功能。

    【讨论】:

      猜你喜欢
      • 2015-02-22
      • 2015-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多