javascript“多态可调用对象” [英] javascript "polymorphic callable objects"
问题描述
我看到了这篇关于多态可调用对象的文章,并试图将其发布到工作,但似乎他们不是真正的多态,或者至少他们不尊重原型链。
I saw this article on polymorphic callable objects and was trying to get it to work, however it seems that they are not really polymorphic, or at least they do not respect the prototype chain.
此代码打印 undefined
,而不是你好
。
此方法不适用于原型,或者是我做错了什么?
Does this method not work with prototypes, or am I doing something wrong?
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);
推荐答案
你需要改变这个:
var X = callableType(function() {
this.callOverload = function(){console.log('called!')};
});
到此:
var X = new (callableType(function() {
this.callOverload = function(){console.log('called!')};
}));
注意 new
以及括号围绕 callableType
调用。
Notice the new
as well as the parentheses around the callableType
invocation.
括号允许 callableType
被调用并返回函数,该函数用作 new
的构造函数。
The parentheses allows callableType
to be invoked and return the function, which is used as the constructor for 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();
我真的不知道你使用这种模式的方式/地点/原因,但我想有一些很好的理由。
I really don't know how/where/why you'd use this pattern, but I suppose there's some good reason.
这篇关于javascript“多态可调用对象”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!