[英]'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.