Reputation: 29
im kinda new at javascript so i have an function which is given an array and it filters its elements from the arguments it is passed. What i need though is to make 'this' inside the callback function to refference at my originalArray so that console.log(this);
would acctually print [1,2,3]. Have in mind that i acctually need to this in these lines because i can only edit all those lines not add some more.
Here is my code:
function makeMultiFilter(array) {
// What we track
// TO BE COMPLETED
// TO BE COMPLETED
return (function arrayFilterer(pred, callback) {
// If filter not a function return current Array
// TO BE COMPLETED
// TO BE COMPLETED
// Filter out things
// TO BE COMPLETED
// If callback is a function, execute callback
// TO BE COMPLETED
// TO BE COMPLETED
return arrayFilterer;
});
}
And the test code:
var arrayFilterer = makeMultiFilter([1, 2, 3]);
// call arrayFilterer to filter out all the numbers not equal to 2
arrayFilterer(function(elem) {
return elem != 2; // check if element is not equal to 2
}, function(currentArray) {
console.log(this); // prints [1,2 3]
console.log(currentArray);
}); // prints [1, 3]`
Upvotes: 1
Views: 377
Reputation: 23372
You can use call
to execute a function in a given this
context:
var callback = function() {
console.log(this);
console.log(arguments);
};
// Using call
callback.call([1,2,3], "A", "B", "C");
// Using apply
callback.apply([1,2,3], ["A", "B", "C"]);
// Using bind:
// creates a new function bound to [1,2,3]
callback.bind([1,2,3])("A", "B", "C");
callback.bind([1,2,3], "A")("B", "C"); // etc.
I guess that in your example code, that would mean that instead of doing callback()
, you'd use callback.call(originalArray)
:
function makeMultiFilter(array) {
// What we track
var originalArray = array;
var currentArray = originalArray;
return (function arrayFilterer(pred, callback) {
// If filter not a function return current Array
if (typeof pred !== "function")
return currentArray;
// Filter out things
currentArray = currentArray.filter(pred);
// If callback is a function, execute callback
if (typeof callback === "function")
callback.call(originalArray, currentArray);
return arrayFilterer;
});
}
var arrayFilterer = makeMultiFilter([1, 2, 3]);
// call arrayFilterer to filter out all the numbers not equal to 2
arrayFilterer(function(elem) {
return elem != 2; // check if element is not equal to 2
}, function(currentArray) {
console.log(this); // prints [1,2 3]
console.log(currentArray); // prints [1,3]
}); // prints [1, 3]`
Upvotes: 2