[英]Do I understand this Function.prototype.call() code correctly?
[英]trying to understand Function.prototype.call in js
<script>
var animals = [
{species: 'Lion', name: 'King'},
{species: 'Whale', name: 'Fail'}
];
for (var i = 0; i < animals.length; i++) {
(function (i) {
this.print = function () {
console.log('#' + i + ' ' + this.species + ': ' + this.name);
}
this.print();
}).call(animals[i], i);
}
</script>
題:
1.為什么這樣寫:this.print,this.species,this.name? 我試圖刪除“ this”,並且在控制台日志中顯示“ undefined”
2. call(animals[i], i)
和call(this, i)
什么區別?
以相反的順序回答您的問題...
(function())。call(...)設置要在其中執行功能的上下文。 即,它將this
對象設置為第一個參數。 在示例中,第一版本設置this
對動物[]陣列中的元素。 第二個將上下文設置為任何this
是-這里將是全球范圍內。
設置上下文后,您的代碼即可使用this
關鍵字引用它。 在您的第一個問題中, this
是指當前的animals []元素,因此它可以提取每種動物的種類,名稱等。 省略this
關鍵字是指未定義的全局范圍內的變量。
你實際上已經創建了一個匿名構造函數,這是this
指的是當您進行匿名構造函數。 使用call(animals[i])
改變的情況下this
每一個對象字面你里面animals
,因為他們通過你的循環數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.