【JavaScript】标签函数

了解标签函数之前我们先简单复习一下模板字符串。

模板字符串

模板字符串语法

在 JavaScript 中编写字符串时,通常使用 ( ' )或者 ( " ),而模板字符串使用 (`)。

例如:

const str1 = 'hello world'
const str2 = 'hello world'

使用模板字符串的语法是:

conststr3 = `hello world`

注意:模板字符串也是字符串。

字符串拼接

普通字符串写法:

var p = {
  name: 'Alfred',
  nn: 'Alfy',
}

console.log("Hi, I'm " + p.name + '! Call me "' + p.nn + '".')

模板字符串写法可以直接使用 ${value} 嵌入表达式:

console.log(`Hi, I'm ${p.name}! Call me "${p.nn}".`)

输出为: Hi, I'm Alfred! Call me "Alfy".

这里可以明显看出模板字符串的优势,不再需要考虑反斜杠来处理单引号和双引号。

换行

模板字符串还有一个很方便的功能是不再需要插入换行符 \n。

普通字符串:

console.log('Dear Mom,\n' + 'Hope you are well.\n' + '\tLove, your son')

模板字符串:

console.log(`Dear Mom,
    Hope you are well.
        Love, your son`)

在模板字符串中所有的换行、tab、空格等字符都是字符串的一部分。

标签函数

标签函数的语法是函数名后面直接带一个模板字符串,并从模板字符串中的插值表达式中获取参数,举个例子。

定义一个 greet 函数接收三个参数。

function greet(arg1, arg2, arg3) {
  console.log(arg1)
  console.log(arg2)
  console.log(arg3)
}

下面两句代码等价

// 普通函数
greet(["I'm ", ". I'm ", " years old."], name, age)

// tag 函数
greet`I'm ${name}. I'm ${age} years old.`、

// 最终输出
[ 'I\'m ', '. I\'m ', ' years old.' ]
Alfred
47

标签函数的第一个参数是被嵌入表达式分隔的文本的数组。第二个参数开始是嵌入表达式的内容。

函数返回标签函数

function cook(strs, ...substs) {
    return substs.reduce(
        (prev,cur,i) => prev+cur+strs[i+1],
        strs[0]
    );
}

function repeat(times) {
    return function (...args) {
        return cook(...args).repeat(times);
    };
}

// 运行结果
> repeat(3)`abc`
'abcabcabc'
> repeat(3)`abc${3+1}`
'abc4abc4abc4'

标签函数返回标签函数

// 实现一个 three 函数
const three = (...args1) => (...args2) => (...args3) =>
    cook(args1) + cook(args2) + cook(args3);

// 我们可以这么调用
> three`hello``world``!`
'helloworld!'

标签函数有什么用

举个例子 styled-components

styled-components 就是通过 Tag 函数来给 React 和 ReactNative 设置 CSS 样式。

posted @ 2021-05-11 18:03  [ABing]  阅读(860)  评论(0编辑  收藏  举报