Answer the question
In order to leave comments, you need to log in
How to change Class.prototype in JS6?
Hello! I'm learning JavaScript. In the process of studying, I came across this example:
function Rabbit() {}
let rabbit = new Rabbit();
// replace the prototype
Rabbit.prototype = {};
// ...not rabbit anymore!
alert( rabbit instanceof Rabbit ); // false
Tell me why the same class trick doesn't work?
class Rabbit {}
let rabbit = new Rabbit();
// replace the prototype
Rabbit.prototype = {};
alert( rabbit instanceof Rabbit ); // true
Rabbit is essentially a constructor function. Every function in JS has a prototype property that points to the prototype object. Why can't I replace this prototype with an empty object in the case of classes? Those. so that it does not contain the constructor property.
Answer the question
In order to leave comments, you need to log in
Because:
function Rabbit() {}
console.log(Object.getOwnPropertyDescriptor(Rabbit, 'prototype')); // { value: {}, writable: true, enumerable: false, configurable: false }
class Rabbit {}
console.log(Object.getOwnPropertyDescriptor(Rabbit, 'prototype')); // { value: {}, writable: false, enumerable: false, configurable: false }
;Rabbit.prototype = {};
TypeError: Cannot assign to read only property 'prototype' of function 'class Rabbit {}'
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question