[英]'this' inside a template literal
根据ES6规范,语法
foo`Hello!`
应该表现得像
foo('Hello!')
将模板文字放在表达式后会触发函数调用,类似于参数列表(括号中用逗号分隔的值)触发函数调用的方式。 前面的代码等效于下面的函数调用(实际上,该函数会获取更多信息,但稍后将进行说明)。
但是,在以下代码段中,将值绑定到函数会导致两种语法的行为有所不同:
function alertParans() { alert(this) } function alertNoParans() { alert `${this}` } var executeParans = alertParans.bind('roman empire'); var executeNoParans = alertNoParans.bind('greek empire'); executeParans(); executeNoParans();
第一个呼叫将打印“罗马帝国”,而第二个呼叫将始终仅打印逗号。 为什么?
您应该阅读链接到的示例,因为该示例与您声明的内容有所不同。
tagFunction`Hello ${firstName} ${lastName}!`
tagFunction(['Hello ', ' ', '!'], firstName, lastName)
现在,如果将其应用于警报,它将看起来像这样:
function alertParans() { alert(['', ''], this); }
function alertNoParans() { alert`${this}`; }
var executeParans = alertParans.bind('roman empire');
var executeNoParans = alertNoParans.bind('greek empire');
executeParans();
executeNoParans();
现在,在两种情况下都可以看到逗号,因为alert
的第一个参数现在始终是带有两个空字符串的数组。 为什么?
因为模板文字会在( ''
)之前,在( this
)期间和( ''
)之后拆分为内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.