javascript“多态可调用对象”

时间:2011-07-03 17:46:46

标签: javascript

我看到this article on polymorphic callable objects并试图让它发挥作用,但似乎它们并不是真正的多态,或者至少它们不尊重原型链。

此代码打印undefined,而不是"hello there"

这种方法不适用于原型,还是我做错了什么?

var callableType = function (constructor) {
  return function () {
    var callableInstance = function () {
      return callableInstance.callOverload.apply(callableInstance, arguments);
    };
    constructor.apply(callableInstance, arguments);
    return callableInstance;
  };
};

var X = callableType(function() {
    this.callOverload = function(){console.log('called!')};
});

X.prototype.hello = "hello there";

var x_i = new X();
console.log(x_i.hello);

1 个答案:

答案 0 :(得分:6)

您需要更改此内容:

var X = callableType(function() {
    this.callOverload = function(){console.log('called!')};
});

到此:

var X = new (callableType(function() {
    this.callOverload = function(){console.log('called!')};
}));

注意new以及callableType调用周围的括号。

括号允许调用callableType并返回函数,该函数用作new的构造函数。


修改

var X = callableType(function() {
    this.callOverload = function() {
        console.log('called!')
    };
});

var someType = X();      // the returned constructor is referenced
var anotherType = X();   // the returned constructor is referenced

someType.prototype.hello = "hello there";  // modify the prototype of
anotherType.prototype.hello = "howdy";     //    both constructors

var some_i = new someType();           // create a new "someType" object
console.log(some_i.hello, some_i);

var another_i = new anotherType();     // create a new "anotherType" object
console.log(another_i.hello, another_i);

someType();      // or just invoke the callOverload
anotherType();

我真的不知道你使用这种模式的方式/地点/原因,但我想有一些很好的理由。