我想要做的是:
function a() {
// ...
}
function b() {
// Some magic, return a new object.
}
var c = b();
c instanceof b // -> true
c instanceof a // -> true
b instanceof a // -> true
是否有可能实现这个目标?我可以通过将a
挂入b
的原型链中轻松地使b
成为a
的一个实例,但是这样我就必须执行new b()
,而我正试图避免这种情况。我想要的东西可能吗?
更新:我觉得通过精确使用b.__proto__ = a.prototype
可能是可行的。下班后我会继续尝试。
更新2:以下是似乎最接近你可以达到的内容,这对我来说已经足够好了。感谢所有有趣的答案。
function a() {
// ...
}
function b() {
if (!(this instanceof arguments.callee)) {
return new arguments.callee();
}
}
b.__proto__ = a.prototype
var c = b();
c instanceof b // -> true
c instanceof a // -> false
b instanceof a // -> true
更新3:我在一篇关于“强大构造函数”的博客文章中找到了我想要的东西,链接如下:blog post on 'power constructors',一旦我添加了必要的b.__proto__ = a.prototype
这一行:
var object = (function() {
function F() {}
return function(o) {
F.prototype = o;
return new F();
};
})();
function a(proto) {
var p = object(proto || a.prototype);
return p;
}
function b(proto) {
var g = object(a(proto || b.prototype));
return g;
}
b.prototype = object(a.prototype);
b.__proto__ = a.prototype;
var c = b();
c instanceof b // -> true
c instanceof a // -> true
b instanceof a // -> true
a() instanceof a // -> true
new
关键字。而且__proto__
对跨浏览器也没有帮助。 - T.J. Crowder