0
function Student() {
}

Student.prototype.sayName = function() {
  console.log(this.name)
}

function EighthGrader(name) {
  this.name = name
  this.grade = 8
}


EighthGrader.prototype = Student.prototype

function NinthGrader(name) {
  this.name = name
  this.grade = 9
}


NinthGrader.prototype = Student.prototype

NinthGrader.prototype.sayName = function() {console.log("HAHAHAHAHAHA")}

const carl = new EighthGrader("carl")
carl.sayName() 

I tried to read the MDN Documentation of Object.create() and i wasn't able to figure out why does console.log(carl.sayName());print "HAHAHAHAHAHA"and not "carl" when i added a method to the prototype object of the NinthGrader object.

  • When you use `new Student`, the JavaScript engine creates a new object and assigns it its prototype using `Student.prototype`. When you use `Object.create(something)`, the JavaScript engine creates a new object and assigns it its prototype using `something`. So in that sense, they're the same thing, although `new Student` also *calls* the `Student` function with the newly-created object so it can initialize it; in contrast, `Object.create` just creates and returns the object. – T.J. Crowder Mar 03 '23 at 09:19
  • 2
    In your code, `Student`, `EighthGrader` and `NinthGrader` share the exact same prototype. `NinthGrader.prototype.sayName = function() {console.log("HAHAHAHAHAHA")}` changes that method for all three of them, because it is one and the same prototype for all three. They are basically three separate constructors for the same (proto-)type. – Thomas Mar 03 '23 at 10:07

0 Answers0