161 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:
- Create a new object whose prototype is taken from the
prototypeproperty of the passed constructor. - Call the constructor with the
thiscontext bound to the newly created object, passing all received arguments. - 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