0

I have a function Person (I use ES5 for this example)

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

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

As I understand, my newly created object ".proto" reference should be equal to Person.prototype (like new operator does). I use Object.create to set appropriate proto. How should I pass additional arguments to my newly created instance so that my 'TestName' argument should be equal to this.name

Create instance function itself:

function createInstance(constructor, ...args) {
  let instance = Object.create(constructor.prototype)
  instance.call(constructor, args)
  return instance
}
let instance = createInstance(Person, 'TestName')
console.log(instance)
s_kamianiok
  • 462
  • 7
  • 24
  • Use `apply` instead of `call`, or just go for the spread operator. Or even better just use `Reflect.construct` :-) – Bergi Oct 13 '19 at 13:45
  • 1
    I i am not mistaken shouldn't it be ```constructor.apply(instance, ...args)``` ? (notice constructor and instance switched) – grodzi Oct 13 '19 at 13:49
  • I guess you're right. That makes sense and works :) – s_kamianiok Oct 13 '19 at 13:51
  • This is an often question from interviews (create an instance without a new operator) also after creating a new instance. instance.__proto__ should be equal to Person.prototype – s_kamianiok Oct 13 '19 at 13:53

0 Answers0