我在javascript有点新,所以我有一个给定数组的函数,它从传递的参数中过滤其元素。我需要的是制作这个'在回调函数内部,在我的originalArray上进行引用,以便console.log(this);
实际打印[1,2,3]。请记住,我在这些行中实际需要这个,因为我只能编辑所有这些行而不再添加更多行。
这是我的代码:
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;
});
}
测试代码:
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]`
答案 0 :(得分:2)
您可以使用call
执行给定this
上下文中的函数:
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.

我想在您的示例代码中,这意味着您不会使用callback()
,而是使用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]`