简体   繁体   English

了解jQuery中的callback.call函数

[英]Understanding callback.call function in jquery

Please go through the below code. 请检查以下代码。 I am not able to exactly what's calllback.call is doing. 我无法确切知道calllback.call在做什么。

Also, I am not able to know what is the difference between this and this[i] and how if(callback.call(this, this[i])) is evaluated to true or false. 另外,我不知道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;
};

The functions are called below: 这些函数如下:

Array.each(function(value){
...
})

Array.map(function(value){
...
})

I am not able to exactly what's calllback.call is doing. 我无法确切知道calllback.call在做什么。

Function.prototype.call lets you invoke a function with an explicit value for this Function.prototype.call允许您this调用具有显式值的函数

callback.call(this, this[i]);

is the same as 是相同的

callback(this[i])

except that inside the callback the value of this is the set to be the same as it was in the current context. 不同之处在于回调内的值this是设定为相同的,因为它是在当前上下文中。


Also am not able to know what is the difference between this and this[i]. 也无法知道this和this [i]有什么区别。

In this context, this is the current array. 在这种情况下, this是当前数组。 So this means the whole array, this[i] gets the i'th element of the array. 因此, this意味着整个数组, this[i]获得数组的第i个元素。


The .each function you have will loop through an array and call a function for each of them. 您拥有的.each函数将遍历数组,并为每个数组调用一个函数。 This is similar to javascript's built in Array.prototype.forEach . 这类似于javascript在Array.prototype.forEach中内置的。

The .map is named as though it were a polyfill for Array.protoype.map but is actually doing a .filter operation. .map的命名就好像它是Array.protoype.map的polyfill一样,但实际上是在执行.filter操作。 Strange. 奇怪。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM