Hi @eoja,
In op’s function expression, he has:
Array.prototype.myMap = function(callback){
var newArray = [];
for (let i=0;i<Array.length;i++){
newArray.push(callback(Array[i]))
}
return newArray;
};
You’ll see he uses Array.length
and Array[i]
, which isn’t declared anywhere. He needs to replace it with this.length
and this[i]
so that the calling object is referenced when myMap
is called.
In his example, he had var new_s = s.myMap(...)
. The myMap(...)
needs to know what array to reference. this
tells the myMap to apply the callback function to the calling array object (in this case, the s
array). But since he used Array
, the .myMap does not know how to access the calling array object; instead it’s trying to access Array
, which isn’t defined anywhere. It’s as if he used Array.myMap(...)
. Even if he did [1, 2, 3].myMap(...)
, [8, 84, 4, 8, 2, 3].myMap(...)
, etc., it will always look at the Array
variable rather than the calling array object.
If you go into your chrome devtool console, copy and paste his code, and try to call it with this example: [1, 2, 3].myMap(num => num * 2)
, you’ll get [NaN]
.
If you change his code just a bit to:
Array.prototype.myMap = function(callback){
var newArray = [];
for (let i=0;i<this.length;i++){
newArray.push(callback(this[i]))
}
return newArray;
};
Copy and paste into the devtools console, and try [1, 2, 3].myMap(num => num * 2)
again, you’ll get [2, 4, 6]. The this
lets .myMap
access the information in the calling [1, 2, 3] object.
Ref: https://javascript.info/object-methods#this-in-methods