Skip to content

Instantly share code, notes, and snippets.

@batogov
Last active October 2, 2017 11:12
Show Gist options
  • Save batogov/74fbf8db6c98bd971526292ce8379610 to your computer and use it in GitHub Desktop.
Save batogov/74fbf8db6c98bd971526292ce8379610 to your computer and use it in GitHub Desktop.
Custom constructor
/*
Кастомный оператор new. Принимает функцию-конструктор и её аргументы.
Возвращает инстанс класса.
*/
function newOperator(constr, args) {
// Создаём объект через Object.create (он наследуется от прототипа конструктора)
// Конструктор не вызывается!
var thisValue = Object.create(constr.prototype);
// Вызывает конструктор, указав в качестве this созданный объект
var result = constr.apply(thisValue, args);
// Если в реализации конструктора переопределено стандартное поведение
// (когда он явно возвращает объект, а не пользуется this), то объект
// будет в result
if (typeof result === 'object' && result !== null) {
return result;
}
return thisValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment