Last active
October 2, 2017 11:12
-
-
Save batogov/74fbf8db6c98bd971526292ce8379610 to your computer and use it in GitHub Desktop.
Custom constructor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Кастомный оператор 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