Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't Object.setProtoypeOf work on functions?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 -> …
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading