I've been learning prototypical inheritance in JavaScript from John Resig's Secrets of the JavaScript Ninja, and I was wondering what happens in the following code example (that I just made up).
function Person() {}
Person.prototype.sayHello = function() {
alert("Hello World");
}
function Ninja() {}
Ninja.prototype.swingSword = function() {
alert("I can swing my sword.");
}
Ninja.prototype = new Person();
var ninja1 = new Ninja();
As far as I know, the result of all of these lines of code is that the variable ninja1
references a Ninja
object, that through its prototype, has the swingSword
method, and through prototypical inheritance of Person
's prototype, has the sayHello
method.
Where I am confused is in the following: since the property swingSword
(which happens to be a method) was attached to Ninja
's prototype before a person instance was assigned to Ninja
's prototype, wouldn't the swingSword
property/method be overwritten by the later assignment of the Person
instance? If not, how can Ninja
's prototype property, which references the prototype object, reference both the Person
instance, and have a swingSword
property?