Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negation of instanceof gives unexpected results

Tags:

javascript

What is the difference between these two statements? They give different output (in google chrome console).

function Test() {
    if (this instanceof Test) {

    } else {
        return new Test();
    }
}
x = Test();

Test {}

function Test() {
    if (!this instanceof Test) {
        return new Test();
    }
}
x = Test();

undefined

Mind = boggled

like image 627
Mike Furlender Avatar asked Dec 26 '13 20:12

Mike Furlender


1 Answers

The issue is that the ! evaluates before the instanceof, so it's being treated as:

if ((!this) instanceof Test) { ... }

And, whether !this is true or false, neither value is an instanceof Test, preventing the new Test() from being returned.

Adding a grouping will force the desired order for "not an instance:"

if (!(this instanceof Test)) { ... }
like image 92
Jonathan Lonowski Avatar answered Oct 04 '22 23:10

Jonathan Lonowski