ООП в JavaScriptThismedium

Полифил оператора new

Пусть у нас есть функция-конструктор, объявляющая класс Person.

function Person(name, age) { this.name = name; this.age = age; } Person.prototype.hello = function () { return `Я ${this.name}, мне ${this.age}, и я учу джаваскрипт.`; };

Мы можем создать экземпляр класса Person с помощью оператора new.

const petya = new Person("Петя", 25); console.log(petya.name); // Петя console.log(petya.age); // 25 console.log(petya.hello()); // Я Петя, мне 25, и я учу джаваскрипт.

Реализуйте функцию nouveau, которая работает так же, как оператор new. Первый её аргумент — функция-конструктор, а остальные — аргументы, с которыми мы хотим вызвать функцию-конструктор.

const petya = nouveau(Person, "Петя", 25); console.log(petya.name); // Петя console.log(petya.age); // 25 console.log(petya.hello()); // Я Петя, мне 25, и я учу джаваскрипт.

Подробнее про метод new можно прочитать на MDN.

Описание поведения с MDN

When a function is called with the new keyword, the function will be used as a constructor. new will do the following things:

  1. Creates a blank, plain JavaScript object. For convenience, let's call it newInstance.
  2. Points newInstance's [[Prototype]] to the constructor function's prototype property, if the prototype is an Object. Otherwise, newInstance stays as a plain object with Object.prototype as its [[Prototype]].
  3. Executes the constructor function with the given arguments, binding newInstance as the this context (i.e. all references to this in the constructor function now refer to newInstance).
  4. If the constructor function returns a non-primitive, this return value becomes the result of the whole new expression. Otherwise, if the constructor function doesn't return anything or returns a primitive, newInstance is returned instead. (Normally constructors don't return a value, but they can choose to do so to override the normal object creation process.)