M
M
Maxim Belousov2021-06-30 22:57:06
JavaScript
Maxim Belousov, 2021-06-30 22:57:06

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

1 answer(s)
I
Inviz Custos, 2021-07-01
@dedavarera

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 }

Find the difference :)
And if you used
'use strict';
it, you would immediately see what the problem is, because when you try to execute
Rabbit.prototype = {};
it, you would get an error:
TypeError: Cannot assign to read only property 'prototype' of function 'class Rabbit {}'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question