Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change Class's Prototype in ES6

Tags:

ecmascript-6

Following is my Class, Its prototype vale is not getting changed, (I am working on the Chrome console)

class Rectangle {
    constructor(length, width) {
        this.length = length;
        this.width = width;
    }

    getArea() {
        return this.length * this.width;
    }

    static create(length, width) {
        return new Rectangle(length, width);
    }
}

and I am Changing the prototype of the Class to null

Rectangle.prototype= null

When I try to access the changed Prototype, the value remains the same "Object" with 'getArea' prototype property of Rectangle

But in ES5 the prototype value is changed.

like image 389
Ignatius Andrew Avatar asked Sep 14 '25 09:09

Ignatius Andrew


1 Answers

In ES6, the .prototype property of classes is not writable and not configurable1. Use strict mode where you do the assignment and you'll get ReferenceError exception "Invalid assignment in strict mode".

If you want to overwrite the .prototype (which is a very bad idea in general), you'll have to use Object.defineProperty(Rectangle, "prototype", {value: …}).

1: See §14.5.14 ClassDefinitionEvaluation, step 16: Perform MakeConstructor(F, writablePrototype=false, prototype=proto).

like image 196
Bergi Avatar answered Sep 17 '25 20:09

Bergi