Object.create 与 new(Class 或构造函数)

Object.create vs. new (Class or constructor function)

我试图区分创建新 object 的方式的某些差异。基本上,您可以通过 object 文字( const obj = {}; )创建一个新的 object 作为某个 class ( const obj = new MyObjClass; )的成员,因为构造函数或通过调用 Object.create().

javascript中的每个实体都是一个object,甚至是函数,因此所有东西都有.__proto__属性,但只有函数可能有(或可能没有).prototype 属性。 Child 的 .__proto__ 属性 等于 parent 的 .prototype 属性。在此类函数的 .prototype 属性 中,您可能会发现 .constructor() 方法,当您使用“new”关键字调用此类函数时会调用该方法。

这适用于 classes 和构造函数:你调用 new YourFunction(),然后在 return 中你会得到一个新的 object,它的 __proto__ 指向到parent的.prototype,也会调用.prototype.constructor(),就是设置最后object.

的属性和方法

但是如果您使用 Object.create() 而不是“new”关键字,是否有可能完全重现“new”关键字的行为?

我在这里尝试重新创建它,它似乎工作正常,但是当你 console.dir() 每个决赛 object 时,你会看到截然不同的结果。所以..

这些创建新 objects 的方式之间的核心区别是什么? 表面之下是否存在某些问题,或者这只是个人喜好的问题?

const objStorage = {}; // just a storage variable so it is easy to pass it to console.dir()

const obj0 = {  // Declaring an object literal, so that we can pass it to Object.create()
  state: "inside Object.create()",
  showState() { console.log("State: " + this.state) }
}

function Obj1() {  // Making constructor function
  this.state = "inside constructor Function()";
  this.showState = function () { console.log("State: " + this.state) }
}

class Obj2 {  // Making class declaration
  constructor() {
    this.state = "inside Class";
    this.showState = function () { console.log("State: " + this.state) }
  }
}

const obj3 = function(){  // Trying to recreate class functionality, so that it can be used both ways
  let self = {};
  self.state = "inside self-made constructor";
  self.showState = function () { console.log("State: " + this.state) }
  return self
};
obj3.prototype = {};
obj3.prototype.constructor = obj3;

objStorage.a = Object.create(obj0); 
objStorage.b = new Obj1; 
objStorage.c = new Obj2; 
objStorage.d = new obj3.prototype.constructor; 
objStorage.e = Object.create(obj3()); 

objStorage.a.showState(); // State: inside Object.create()
objStorage.b.showState(); // State: inside constructor Function()
objStorage.c.showState(); // State: inside Class
objStorage.d.showState(); // State: inside self-made constructor
objStorage.e.showState(); // State: inside self-made constructor

Object.create() and the new 运算符之间的主要区别在于,虽然它们都使用从传递的原型对象派生的原型链创建对象,但只有 new 运算符使用新创建的对象调用构造函数对象应用为 this,而 Object.create() 不应用。

以下是这种差异影响的几个演示:

const a = new Array();
const b = Object.create(Array.prototype);

console.log(Array.isArray(a));
console.log(Array.isArray(b));

const c = new Map();
const d = Object.create(Map.prototype);

console.log(c.set('foo', 'bar'));
console.log(d.set('foo', 'bar'));

在大多数情况下,应该没有理由直接使用Object.create()。构造函数经常初始化对象按预期工作所必需的内部成员。

要回答您的其他问题,不,new 无法使用 Object.create() 完全重新创建,但可以使用 Reflect.construct() 代替。