簡體   English   中英

試圖了解js中的Function.prototype.call

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

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call?redirectlocale=zh-CN&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fcall

題:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM