我可以在不使用new关键字的情况下构建一个JavaScript对象吗?

11 浏览
0 Comments

我可以在不使用new关键字的情况下构建一个JavaScript对象吗?

我想做的是:

function a() {
  // ...
}
function b() {
  // 一些魔法,返回一个新对象。
}
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:我在一篇关于“强大构造函数”的博文中找到了我想要的内容,只要我添加了关键的`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

0