Strange behaviour of JavaScript in Chrome Develope

2020-03-14 07:59发布

Recently, working with JavaScript in Developer Tool, I found strange feature. Chrome accepts any code between opening bracket with operator (plus, minus sign) and operator with closing brackets and executes it, like this: enter image description here

I didn't find this behaviour in another browsers, just in Chrome.

Maybe it's a feature, but why and how it works, can it be problem with JavaScript engine?

2条回答
家丑人穷心不美
2楼-- · 2020-03-14 08:47

This happens because Chrome wraps the code you enter in the console in the following construction:

with (typeof __commandLineAPI !== 'undefined' ? __commandLineAPI : { __proto__: null }) {
  // Your code
}

So, when you enter something like } 10 {, the code evaluates to:

with (typeof __commandLineAPI !== 'undefined' ? __commandLineAPI : { __proto__: null }) {
  } 10 {
}

which is empty with block, a number, and empty structural block.

__commandLineAPI is the internal object that contains Chrome Command Line API.

查看更多
姐就是有狂的资本
3楼-- · 2020-03-14 09:06

This is the way chrome evaluates your input:

with (typeof __commandLineAPI !== 'undefined' ? __commandLineAPI : { __proto__: null }) {
 // your code here...
}

So once your input is }{ it becomes

with (typeof __commandLineAPI !== 'undefined' ? __commandLineAPI : { __proto__: null }) {}{} // indefined

Next input }-+{ becomes

undefined -+ {} // NaN

And so on.

查看更多
登录 后发表回答