ES6的String.raw的原理实现
ES6版本相比于ES5增加了很多新的东西,可以大大提升开发者的开发效率。当然,在用好这些新东西的同时,探究其内部实现原理能更好地帮助我们的视野和逻辑能力。今天我们来看看ES6的原始字符串的知识。
阅读这篇文章你至少需要了解一下知识:
- ES6模板字符串
- 标签函数
当然,如果你对以上知识还不太熟悉,可以花几分钟阅读下MDN的模板字符串相关文档。OK,Let's go!
开始String.raw
首先应该明确一点:String.raw是官方提供的标签函数,类似于Python中的r前缀,旨在更方便地得到获取原始的模板字面量内容。先来简单看一下String.raw的用法
console.log(`\u00A9`); // ©
console.log(String.raw`\u00A9`); // \u00A9,注意第一个\是普通反斜杠
console.log(String.raw`\u00a9`.length); \\ 6
console.log(`first line\nsecond line`);
//first line
//second line
console.log(String.raw`first line\nsecond line`); // first line\nsecond line
通过例子我们可以看到,在模板字符串前使用String.raw标签函数可以将字符串中\n、\t以及16进制表示的Unicode字符原样返回,即所谓原始字符串。
String.raw语法
String.raw`templateStr`
String.raw(callSite, ......substitutions)
参数
templateStr
ES6新增的模板字符串,可以包含占位符(${})
callSite
亿个模板字符串的“调用点对象,“,类似`{raw:'test'}`
substitutions
任意可选参数,表示任意插值内的值
返回值
返回给定模板字符串或传入参数的字符串形式,其中包含原始字符串
通常情况下我们都是搭配模板字符串来使用该标签函数,第二种调用方式是为了模拟其用法,引擎会在背后调用该标签参数来完成对模板字符串的转换。
let name = "Bob";
console.log(String.raw`Hi\n${name}`);
// "Hi\bBob!"
//模拟`t${0}e${1}s${2}t`,也可以显示调用标签函数
String.raw({raw:"test"}, 0, 1, 2) // t0e1s2t
注意细节
-
只能显式地获取原始模板字符串内容,而不是其转换后的字符表示。比如:
// 该示例不会显示原始字符串 console.log(String.raw`first line second line`); // first line // second line
标签函数目前不支持IE系列
原理实现
String.raw本质上就是一个函数,只不过更多用来处理模板字符串,根据其第二种语法尝试写出其内部实现原理如下:
String.raw = function(strings, ...values) {
if (typeof strings.raw == "undefined") {
throw "TypeError: Cannot convert undefined or null to object";
}
var output = "",
len = strings.raw.length - 1;
if (len < 0) {
return output;
}
for (var idx = 0; idx < len; idx++) {
output += strings.raw[idx] + (values[idx] ? values[idx] : "");
}
output += strings.raw[idx];
return output;
}
相关链接
End...