Last active
April 4, 2017 10:27
-
-
Save dolvik/213c0f349c178a58c4f8b871acbd2064 to your computer and use it in GitHub Desktop.
Inheritence in Javascript
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
//Раньше наследование делали с помощью такой функции-помощника. | |
//Вся цель этой функции - присвоить свойству prototype дочернего класса новый объект, прототип которого будет ссылаться на свойство prototype объекта parent | |
function inherit(child, parent){ | |
//создается вспомагательная функция, т.е. объект типа Function | |
function F(){}; | |
//объект типа Function имеет свойство prototype, которое мы перезаписываем на parent.prototype | |
F.prototype = parent.prototype; | |
//создаем новый объект, прототипом которого будет F.prototype, который в свою очередь ссылается на parent.prototype | |
//т.е. new F() создает объект obj: | |
//obj.__proto__ = parent.prototype | |
//obj.__proro__.constructor = parent | |
//и присваиваем этот новый оъект свойству prototype дочернего класса | |
child.prototype = new F(); | |
//если бы мы этим и ограничились, то при создании объектов new child(), вызывался бы конструктор parent | |
//но т.к. мы хотим, чтобы вызывался конструктор child, то переписываем свойсво constructor у прототипа child | |
child.prototype.constructor = child; | |
} | |
//Новый подход | |
function inherit(child, parent){ | |
child.prototype = Object.create(parent.prototype); | |
child.prototype.constructor = child; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment