I'm working on a JavaScript problem that involves hiding a parameter to demonstrate how this works.
The problem involves searching for an array, [1,2], in a search space which is a multidimensional array, e.g [[2,3], [3,4]]. However, the search space is passed in as part of this value to the function.
Function definition:
function contains(cell) {}
How do I access the search space passed in as this to the function? The accompanying testcase uses bind() to pass in the search space e.g
contains.bind([[2,3], [3,4]])
Here is the attempt at completing the function:
function contains(cell){
let found = false;
[x, y] = cell;
// How do I access searchSpace passed in through `this`?
searchSpace.forEach((element) => {
[j, k] = element;
// match first occurrence in array
if (x === j && y === k){
found = true;
}
});
return found;
}
How do I invoke the function:
// contains(cell)
contains([1,2])
You should be able to pass that value as a variable to the contains function. this refers to something different in and out of the function (see this question for more context).
The easiest approach would be:
function contains(cell, searchSpace){
let found = false;
[x, y] = cell;
// How do I access searchSpace passed in through `this`?
searchSpace.forEach((element) => {
[j, k] = element;
// match first occurrence in array
if (x === j && y === k){
found = true;
}
});
return found;
}
contains([1,2], this.searchSpace);
If you want to bind [[2,3], [3,4]] as this to the contains function it would be contains.bind([[2,3], [3,4]]) and not contains().bind([[2,3], [3,4]]).
And bind does not change the function on which it is called directly so contains.bind([[2,3], [3,4]]) alone and then calling contains won't do anything.
bind returns a new function, and that function then calls contains with the given value as this.
How do I access the search space passed in as
thisto the function?
By using this in the function.
function contains(cell) {
console.dir(this)
console.dir(cell)
}
const containsWithBind = contains.bind([[2,3], [3,4]])
containsWithBind([1,2])
How your code attempt should look like:
function contains(cell){
let found = false;
[x, y] = cell;
// How do I access searchSpace passed in through `this`?
this.forEach((element) => {
[j, k] = element;
// match first occurrence in array
if (x === j && y === k){
found = true;
}
});
return found;
}
const containtsWithBind = contains.bind([[2,3], [3,4]])
// contains(cell)
console.log(containtsWithBind([1,2]))
console.log(containtsWithBind([2,3]))