javascript - 我可以在不使用 new 关键字的情况下构造 JavaScript 对象吗?

标签 javascript inheritance prototype constructor

这是我想做的:

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 挂接到其原型(prototype)链中,轻松地使 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

最佳答案

您可以使用此模式:

function SomeConstructor(){
   if (!(this instanceof SomeConstructor)){
        return new SomeConstructor();
   }
   //the constructor properties and methods here
}

之后您可以执行以下操作:

var myObj = SomeConstructor();

[编辑 2023(实际上:重新编辑)] 要完全避免使用 new 关键字,您可以使用 factory function 。这是一个例子。这就是 Douglas Crockford 所说的 class free object oriented solution .

该模式/想法在this small github repository内使用

const Person = (name = 'unknown', age = 0, male = false) => {
  const value = () => `This is ${name}. ${
    !male ? `Her` : `His`} age is ${age} years.`;
    
  return {
    get whoIs() { return value(); },
    toString() { return value(); },
    addAge: years => age += years,
    setAge: newAge => age = newAge,
    rename: newName => name = newName,
  };
}
// usage
const [ jane, charles, mary ] =  [
  Person(`Jane`, 23), 
  Person(`Charles`, 32, 1), 
  Person(`Mary`, 16), ];

jane.addAge(17);
charles.setAge(76);
console.log(`${jane}`);
console.log(`${mary}`);
console.log(charles.whoIs);

关于javascript - 我可以在不使用 new 关键字的情况下构造 JavaScript 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26616071/

相关文章:

javascript - 如何在另一个函数中调用onchange函数

javascript - 在文本框中显示弹出提示的内容?

C++ 继承/VTable 问题

javascript - JavaScript 中类的嵌套和 this 值

javascript - 在 Firefox 中定义自定义键

c++ - 如何创建一个 C++ 类来基于不同的相似类执行相同的计算?

xcode - 为什么在子类化和抽象实体时必须设置父实体?

javascript - 扩展原型(prototype)数组

javascript - 如何使用原型(prototype)创建原始包装对象

javascript - crossdomain.xml 配置