Lynn
Lynn

Reputation: 453

How can [this] be undefined in strict mode?

When I run this code in Chrome, I get an Uncaught TypeError: Cannot read property 'concat' of undefined

function _log()
{
    'use strict'

    [this].concat(Array.from(arguments)).forEach(
        function (obj) { console.log(obj) }
    )
}

_log('foo', 'bar');

I don't understand why this is happening. How can [this] be undefined? Even if this were undefined, [this] should still be an array, shouldn't it?

A funny detail is that when I remove the use strict line from the function, the error disappears and the code behaves as expected, logging the function context and arguments each on a new line.

Is there maybe something special about using the keyword this in strict mode which I'm not aware of?

Thanks.

Upvotes: 4

Views: 609

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382274

This is a fun bug:

You just forgot the semicolon after 'use strict', which totally changes how the code is parsed:

'use strict'[this].concat...

You're taking the property named "[Object window]" in the 'use strict' chain. Of course it's undefined, so it doesn't have any property called "concat".

Upvotes: 7

Related Questions