admin管理员组

文章数量:1336293

I was messing around with some ES6-code and came across this

let vendors = ['ms', 'moz', 'webkit', 'o'];
let root = window || global;
let performance = window.performance || {};
if (!performance.now) {
  vendors.some(function(vendor) {
    performance.now = performance[`$[vendor}Now`];
    ...

I can guess what the code-piece below does, but what kind of library/syntax is it? It's not something I have ever seen before, and it's not pure ES6, right?

`$[vendor}Now`

I was messing around with some ES6-code and came across this

let vendors = ['ms', 'moz', 'webkit', 'o'];
let root = window || global;
let performance = window.performance || {};
if (!performance.now) {
  vendors.some(function(vendor) {
    performance.now = performance[`$[vendor}Now`];
    ...

I can guess what the code-piece below does, but what kind of library/syntax is it? It's not something I have ever seen before, and it's not pure ES6, right?

`$[vendor}Now`
Share edited Sep 13, 2015 at 16:29 user663031 asked Sep 13, 2015 at 10:59 Alfred GårdeskogAlfred Gårdeskog 751 silver badge7 bronze badges 2
  • 2 Looks like a mistake. Ask the author of the code. – Bergi Commented Sep 13, 2015 at 12:31
  • In addition to being a syntax error, all this is unnecessary, since webkit is the only platform that apparently ever used performance.webkitNow, and that was way back in v20. – user663031 Commented Sep 13, 2015 at 16:28
Add a ment  | 

1 Answer 1

Reset to default 11

It seems that this is a syntax error. The correct thing should be:

`${vendor}Now`

This is the dollar expression as it is mentioning here: https://developer.mozilla/en/docs/Web/JavaScript/Reference/template_strings

Template strings are enclosed by the back-tick (`) (grave accent) character instead of double or single quotes. Template strings can contain place holders. These are indicated by the Dollar sign and curly braces (${expression}).

The square bracket in a template string is a mistake.

More specifically if you have:

var expression = 'test';

console.log(`string text ${expression} string text`); //Correct syntax

The above code will export: "string text test string text"

But the below code with one opening square bracket and one closing curly bracket

var expression = 'test';

console.log(`string text $[expression} string text`); //Wrong syntax

Will just export: "string text $[expression} string text"

本文标签: javascriptDollar sign followed by a square bracket in a template stringStack Overflow