Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Class extending native type makes instanceof behave unexpectedly in some JavaScript engines?

Consider the following ES6 Classes:

'use strict';

class Dummy {
}

class ExtendDummy extends Dummy {
    constructor(...args) {
        super(...args)
    }
}

class ExtendString extends String {
    constructor(...args) {
        super(...args)
    }
}

const ed = new ExtendDummy('dummy');
const es = new ExtendString('string');

console.log(ed instanceof ExtendDummy);
console.log(es instanceof ExtendString);

My understanding is that both should be true, and in Firefox and Chrome they are, however Node says es instanceof ExtendString is false. It's the same with other constructors, not just String.

Software I used:

  • Node v5.11.0 with the --harmony flag.
  • Chrome 50
  • Firefox 45

Which JavaScript engine is correct and why?

like image 286
Alexander O'Mara Avatar asked Apr 26 '16 20:04

Alexander O'Mara


People also ask

Which JavaScript feature is the alternative to ES6 classes the class keyword )?

The function keyword is replaced with the class keyword. There's a special function named 'constructor' where the initialization of the object is done.

Can JavaScript class extend function?

Definition and UsageThe extends keyword is used to create a child class of another class (parent). The child class inherits all the methods from another class. Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.

How does Instanceof work in JavaScript?

The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value. Its behavior can be customized with Symbol. hasInstance .

Which of the below does ES6 class not support?

ES6 doesn't support multiple inheritance. Multi-level − Consider the following example.


1 Answers

Node appears to be incorrect, es instanceof ExtendString should definitely be true (like everyone would expect).

String[Symbol.hasInstance] is not overwritten, and Object.getPrototypeOf(es) should be ExtendedString.prototype, as the spec details this in the String (value) function description:

  1. Return StringCreate(s, GetPrototypeFromConstructor(NewTarget, "%StringPrototype%")).

The newtarget refers to ExtendString when you construct the new ExtendString('string') instance, and since it is a constructor with a .prototype object it will use ExtendedString.prototype not %StringPrototype as the [[prototype]] for the newly created exotic String object:

  1. Set the [[Prototype]] internal slot of S to prototype.
like image 55
Bergi Avatar answered Sep 23 '22 17:09

Bergi