首页 > 解决方案 > 如何在不调用构造函数和 new 关键字的情况下创建对象

问题描述

我有一个函数 Person(我在这个例子中使用 ES5)

function Person(name) {
  this.name = name
}

Person.prototype.printName = function() {
  console.log(this.name)
}

据我了解,我新创建的对象“ .proto”引用应该等于 Person.prototype (就像 new 运算符一样)我使用 Object.create 设置适当的proto。我应该如何将其他参数传递给我新创建的实例,以便我的“TestName”参数应该等于 this.name

创建实例函数本身:

function createInstance(constructor, ...args) {
  let instance = Object.create(constructor.prototype)
  instance.call(constructor, args)
  return instance
}
let instance = createInstance(Person, 'TestName')
console.log(instance)

标签: javascriptecmascript-6

解决方案


推荐阅读