【发布时间】:2010-12-25 17:32:59
【问题描述】:
这是我想做的:
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 成为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
【问题讨论】:
-
我很好奇:你为什么要避免新的?
-
我正在创建 Scala 案例类的 Javascript 版本:github.com/pr1001/caseclass.js
-
@pr1001:不明白为什么这需要您解决
new关键字。而__proto__不会帮助你跨浏览器。 -
这都是语法糖,仅此而已。但是,我认为这仍然是一个有趣的挑战。
标签: javascript inheritance prototype constructor