[英]Understanding callback.call function in jquery
請檢查以下代碼。 我無法確切知道calllback.call在做什么。
另外,我不知道this和this [i]有什么區別,以及if(callback.call(this,this [i]))如何被評估為true或false。
Array.prototype.each = function(callback) {
var i = 0;
while (i < this.length) {
callback.call(this, this[i]);
i++;
}
return this;
};
Array.prototype.map = function(callback) {
var i = this.length;
var found = []
while (i--) {
if(callback.call(this, this[i])) {
found.push(this[i]);
}
}
return found;
};
這些函數如下:
Array.each(function(value){
...
})
Array.map(function(value){
...
})
我無法確切知道calllback.call在做什么。
Function.prototype.call允許您this
調用具有顯式值的函數
callback.call(this, this[i]);
是相同的
callback(this[i])
不同之處在於回調內的值this
是設定為相同的,因為它是在當前上下文中。
也無法知道this和this [i]有什么區別。
在這種情況下, this
是當前數組。 因此, this
意味着整個數組, this[i]
獲得數組的第i個元素。
您擁有的.each
函數將遍歷數組,並為每個數組調用一個函數。 這類似於javascript在Array.prototype.forEach中內置的。
.map
的命名就好像它是Array.protoype.map的polyfill一樣,但實際上是在執行.filter操作。 奇怪。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.