I am having trouble to understand something. I have been looking for a while about the differences but I can't seem to find the answer I am looking for.
I am trying to learn OOP javascript and every tutorial I read there seems to be a different way of doing inheritance and it is often explained in a very complicated way. The problem I am stuck on now has to do with creating methods for an object, I am using the code from the Mozilla developer documentation.
You will see in the large code block below that I tried to add a jump method in the Person like this:
Person.prototype = {
jump: function() {
console.log("Jumping")
}
}
This doesn't work it basically breaks the entire class telling me that student1.walk is not a function. However if I change the declaration of the method to
Person.prototype.jump = function() {
console.log("Jumping");
}
Everything works like it should when I call the methods. From a personal style standpoint though I like the first way of creating methods because I don't have to keep repeating the Person.prototype portion I can just keep adding a comma followed by my method declaration. I am wondering what the difference is between these two ways of creating methods because I can't find the answer anywhere. I want to understand why it breaks using the first method as well.
var Person = function(firstName) {
this.firstName = firstName;
};
Person.prototype.walk = function(){
console.log("I am walking!");
};
Person.prototype = {
jump: function() {
console.log("Jumping");
}
}
Person.prototype.sayHello = function(){
console.log("Hello, I'm " + this.firstName);
};
function Student(firstName, subject) {
Person.call(this, firstName);
this.subject = subject;
}
Student.prototype = Object.create(Person.prototype); // See note below
Student.prototype.constructor = Student;
Student.prototype.sayHello = function(){
console.log("Hello, I'm " + this.firstName + ". I'm studying "
+ this.subject + ".");
};
Student.prototype.sayGoodBye = function(){
console.log("Goodbye!");
};
var student1 = new Student("Janet", "Applied Physics");
student1.sayHello();
student1.walk();
student1.sayGoodBye();
student1.jump();
Person.prototype = {...}overrides the prototype. You can doObject.assign(Person.prototype, {...})prototypeyou have to assign a new method in your casejump