C
C
Coder3212018-03-05 11:17:47
JavaScript
Coder321, 2018-03-05 11:17:47

How to make the base class inherit?

I'm trying to create my own class that will inherit from String, but there are problems.
This option works in the browser but does not work in React Native but for some reason this option does not work anywhere
class MyString extends String { }

function MyString() { }
MyString.prototype = Object.create(String.prototype)

The error pops up like this:
Uncaught TypeError: String.prototype.toString requires that 'this' be a String
What could be the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
youngmysteriouslight, 2018-03-08
@Coder321

There is such. Opera, for example, shouts:
According to the specification , toString throws an exception if this is not a string, that is, roughly

String.prototype.toString = function() {
  if (typeof this === 'string')
    return this.valueOf();
  else
    throw new TypeError();
};

To be able to inherit from String, you need to override the method.
PS I can't explain why the code with extend works.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question