I saw 这篇关于多态可调用对象的文章 http://ajaxian.com/archives/javascript-tips-for-rookies-and-gurus并试图让它工作,但似乎它们并不是真正的多态,或者至少它们不尊重原型链。
这段代码打印undefined
, not "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);
你需要改变这个:
var X = callableType(function() {
this.callOverload = function(){console.log('called!')};
});
to this:
var X = new (callableType(function() {
this.callOverload = function(){console.log('called!')};
}));
注意new
以及周围的括号callableType
调用。
括号允许callableType
被调用并返回函数,该函数用作构造函数new
.
EDIT:
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();
我真的不知道你如何/在哪里/为什么使用这种模式,但我想有一些很好的理由。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)