Please go through the below code. I am not able to exactly what's calllback.call is doing.
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.
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.
Function.prototype.call lets you invoke a function with an explicit value for 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.
Also am not able to know what is the difference between this and this[i].
In this context, this
is the current array. So this
means the whole array, this[i]
gets the i'th element of the array.
The .each
function you have will loop through an array and call a function for each of them. This is similar to javascript's built in Array.prototype.forEach .
The .map
is named as though it were a polyfill for Array.protoype.map but is actually doing a .filter operation. Strange.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.