2011-07-03 46 views
7

我看到this article on polymorphic callable objects,并试图让它工作,但它似乎并不是真正的多态,或者至少他们不尊重原型链。javascript“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

我刚刚对你的肖像和名字印象深刻。我想他的名字舒仁周。 – xis

回答

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(); 

我真的不知道如何/在哪里/为什么你会使用这个模式,但我想有一些很好的理由。

+0

也许我做错了什么,但这似乎打破了能够调用实例调用'x_i()'抛出一个异常沿“对象不功能”的行。 –

+0

@luxun:通过像这样内联使用'new',您可以立即调用从'callableType'返回的函数作为构造函数。我认为你所缺少的是你的代码被添加到'X'的原型而不是从'X'返回的构造函数。按照我的方式,'X'本身就是构造函数,但是您可以用另一个变量来引用它。我将添加更新。 – user113716

+0

好的,我明白了。我实际上认为它会使*实例*可调用,但我认为情况并非如此。 –