Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax Error when call Error.constructor with a string including spaces

I tried the following code in firefox & chrome & Node.js:

Error.constructor.call({}, 'specified string'); // Uncaught SyntaxError: Unexpected identifier
Error.constructor.call({}, 'specified '); // work well
Error.constructor.call({}, 'specified'); // work well

I wonder the reason JS interpreter giving me that Error. It seems that eval() is called with the second parameter, but I really don't know what happened.

like image 804
Claim Yang Avatar asked Jan 26 '26 08:01

Claim Yang


1 Answers

First off, Error.constructor is actually Object.constructor:

> Error.constructor === Object.constructor
true

Second, Object.constructor can be used to create a function:

> f = Object.constructor('foo', 'bar', 'return "hello " + foo + " and " + bar;')
[Function: anonymous]
> f('Alice', 'Bob')
'hello Alice and Bob'

where the last parameter is the function body and the previous parameters are function parameters.

Finally, your code:

Error.constructor.call({}, 'specified string');

means you are calling Object.constructor to create a function with a function body specified string. The function body specified string is a piece of invalid JavaScript code, hence the error.

like image 103
johnlinp Avatar answered Jan 27 '26 22:01

johnlinp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!