InterviewSolution
| 1. |
var hero = { _name: 'Johnny Deep', getIdentity: function (){ return this._name; } }; var heroIdentity = hero.getIdentity; console.log(heroIdentity()); console.log(hero.getIdentity()); |
|
Answer» We can implement the Array.prototype methods by using callbacks and actually this is the way it is implemented in JavaScript internally. forEach We are implementing our version of forEach as myEach by having the callback attached to the prototype, which is available to every JS function. Here “this” is equal to the array. So, we are iteration over it using traditional for loop and calling the callback function on each iteration. map We are implementing our version of map as myMap, by creating an empty array in our function and then pushing it in the iteration. From inside the push we are calling our callback, so when we are calling it we can use SOMETHING like Math.round(line 17) to change an individual item or just return it like in line 13. filter We are implementing our version of filter as myFilter. The process is quite similar to map, where we create an empty array ad push to it. But as we KNOW that filter GOES through the array and gives an subset of ELEMENTS depending on BOOLEAN expression. |
|