I’m trying to understand inheritance in JavaScript. I’m using prototype to link a child class to it’s parent. But as soon as I’m defining the relationship the constructor of the parent class starts running.
<script type="text/javascript">
function Person ()
{
window.alert('We\'ve got a new person!');
}
function King ()
{
window.alert('We\'ve got a new king!');
}
King.prototype = new Person();
//King.prototype.constructor = King;
//var erik = new King();
</script>
What’s the correct way of using inheritance in JavaScript?
The tutorial that started the confusion: https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript
That’s because Javascript is a prototyped language and doesn’t really support inheritance in that way. It’s objects are loose types that can be extended with extra functions and properties on the fly.
So what you actually do, is create an
instanceof Person, which can then be extended with extra methods.The tuturial states this:
It is rather confusing if you are used to real (well, class based) OO.