Let's say we have the below code:
"use strict";
function Student() {}
Student.prototype.sayName = function () {
console.log(this.name);
};
function EighthGrader(name) {
this.name = name;
this.grade = 8;
}
Object.setPrototypeOf(EighthGrader, Student.prototype);
const carl = new EighthGrader("carl");
carl.sayName(); // Uncaught TypeError: carl.sayName is not a function
why doesn't Object.setPrototypeOf
work on function if all all function in JavaScript are also objects?
CodePudding user response:
The setPrototypeOf
method works just fine on functions, you can now do EighthGrader.sayName()
(which will say the EightGrader
function's .name
) and can no longer do EighthGrader.call()
which was previously inherited from Function.prototype
.
It's just that you didn't want to use it on the function, but rather on the prototype object that carl
inherits from. To do that, you'll have to use
Object.setPrototypeOf(EighthGrader.prototype, Student.prototype);
The prototype chain of carl
is
carl -> EighthGrader.prototype -> …
not
carl -> EightGrader -> …