OOP Javascript:内置与用户定义的构造函数

OOP Javascript: Built in vs User defined Constructor

我正在尝试了解 javascript 中的对象创建,我知道我们有几种方法可以实现它:对象文字、工厂和构造函数。

/***********************************************/
/***********************************************/
// Literal - Singleton
const obj_lit = {
  log_lit: function() {
    //console.log("Obj Literal");
    document.write("Obj Literal<br>");
  }
};
obj_lit.log_lit();
/***********************************************/
/***********************************************/
// Factory - Explicit Return
function objFac() {
  return {
    log_fac: function() {
      //console.log("Obj Factory");
      document.write("Obj Factory<br>");
    }
  };
}
const obj_fac = objFac();
obj_fac.log_fac();
/***********************************************/
/***********************************************/
// Constructors - Implicit Return
function ObjCon() {
  this.log_con = function() {
    //console.log("Obj Constructor");
    document.write("Obj Factory<br>");
  }
}
const obj_con = new ObjCon();
obj_con.log_con();

我实际上是在使用控制台,但在 jsfiddle 中我通过 doc write 输出

问题是,与我们显式使用 obj 构造函数类型的方式相比,我们不通过构造函数处理 obj 文字和工厂。到目前为止一切顺利,但是当我在控制台中检查 obj 文字和工厂时,它们确实有一个构造函数 [native code]

这是我在控制台中得到的:

obj_lit.constructor
ƒ Object() { [native code] }

obj_fac.constructor
ƒ Object() { [native code] }

obj_con.constructor
ƒ ObjCon() {
  this.log_con = function() {
    console.log("Obj Constructor");
  }
}

那么 obj_lit 和 obj_fac 的这两个原生构造函数到底是什么?

js 引擎实际上是通过内部 'new' 关键字创建 obj_lit 和 obj_fac 吗?

当我们不想采用通过构造函数创建对象的经典方法时,它不会破坏使用文字和工厂的整个概念吗?

So what really are those 2 native constructors for obj_lit and obj_fac?

{} 等价于 new Object.

and is the js engine actually creating the obj_lit and obj_fac via an internal 'new' keyword?

或多或少。这是一个实现细节。

and wouldn't it break the whole concept of using literal and factories when we don't want to go for the classic way of creating objects via constructors?

没有。

原型继承是 JavaScript 的基本特征。

如果您开始修改对象原型,它只会破坏事物。如果你不想使用 JS 的 OO 特性,那么你就不会这样做。