Skip to content
Junior–Senior161 views

Creating your own analogue of the new operator

Task condition

Write a function createInstance that takes a constructor (e.g., Book) as its first parameter and an arbitrary number of additional arguments. The function should:

  1. Create a new object whose prototype is taken from the prototype property of the passed constructor.
  2. Call the constructor with the this context bound to the newly created object, passing all received arguments.
  3. Return the created object, which should be an instance of the passed constructor.
function Book(name, author) {
  this.name = name;
  this.author = author;
}

function createInstance(Constructor, ...args) {
  // Your code here
}

const myBook = createInstance(Book, 'JavaScript Textbook', 'Peter Sergeev');

console.log(myBook); // { name: 'JavaScript Textbook', author: 'Peter Sergeev' }
console.log(myBook instanceof Book); // true
Frontend tasks in the code trainer