denysdovhan / wtfjs

🤪 A list of funny and tricky JavaScript examples
http://bit.ly/wtfjavascript
Do What The F*ck You Want To Public License
34.95k stars 2.55k forks source link

Update README.md #105

Closed geekjob closed 3 years ago

geekjob commented 5 years ago
// Declare a class which extends null
class Foo extends null {}
// -> [Function: Foo]

new Foo() instanceof null;
// > TypeError: function is not a function

Not a bug! Because it is feature:

console.dir(Object.getPrototypeOf(Foo.prototype)); // is null

if the class has no constructor the call from prototype chain. But in the parent has no constructor. Just in case, I’ll clarify that null is an object. Therefore, you can inherit from it (although in the world of the OOP for such terms would have beaten me).

So you can't call the null constructor.

If you change this code:

class Foo extends null {
    constructor() {
        console.log(111);
    }
}

You se the error:

ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

And if add super:

class Foo extends null {
    constructor() {
        console.log(111);
        super();
    }
}

JS throw error:

TypeError: Super constructor null of Foo is not a constructor

This is my explanation based on my experience and understanding how the JS works.

denysdovhan commented 5 years ago

I think we should extend function is not a function section with this explanation.

denysdovhan commented 3 years ago

Closed due to no activity. Feel free to reopen.