本文介绍了ES6标签模板实用可用性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解ES6的语法。我看不到的是实用的可用性。什么时候比传递对象参数更好,像中的设置? $。ajax('url',{/ *这个人在这里* /})

I understand the syntax of ES6 tagged templates. What I don't see is the practical usability. When is it better than passing an object parameter, like the settings in jQuery's AJAX? $.ajax('url', { /*this guy here*/ })

看到棘手的语法,但我不明白为什么我需要/使用它。我还发现,在其他重要功能之前,TypeScript团队选择实现它(1.5)。标记字符串模板背后的概念是什么?

Right now I only see the tricky syntax but I don't see why I would need/use it. I also found that the TypeScript team chose to implement it (in 1.5) before other important features. What is the concept behind tagged string templates?

推荐答案

您可以使用标记的模板来构建比常规函数调用更具表现力的API。

You can use tagged templates to build APIs that are more expressive than regular function calls.

例如,我正在开发一个用于JS数组上的SQL查询:

For example, I'm working on a proof-of-concept library for SQL queries on JS arrays:

let admins = sql`SELECT name, id FROM ${users} 
                 WHERE ${user => user.roles.indexOf('admin') >= 0}`

请注意,用String插值;它使用标记的模板进行可读性。通过简单的函数调用,很难构造出直观的东西 - 我猜你会有这样的东西:

Notice it has nothing to do with String interpolation; it uses tagged templates for readability. It would be hard to construct something that reads as intuitively with plain function calls - I guess you'd have something like this:

let admins = sql("SELECT name, id FROM $users WHERE $filter",
  { $users: users, $filter: (user) => user.roles.contains('admin') })

这个例子只是一个有趣的方面的项目,但我认为它显示了标记模板的一些好处。

This example is just a fun side project, but I think it shows some of the benefits of tagged templates.

另一个例子,也许更明显的是i18n - 标记的模板可以插入区域设置敏感的输入版本。

Another example, maybe more obvious, is i18n - a tagged template could insert locale-sensitive versions of your input.

这篇关于ES6标签模板实用可用性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 07:04