Knowing how you can manipulate
this gives you great power and you no more have to write
var self = this.
See for example this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Now if you try to run that code in your node.js environment, it will give you the following error:
1 2 3 4
This comes because the addFile method was not found on the this keyword. So what is then exactly the this keyword now? Lets try it and log it to the console:
1 2 3 4 5 6 7 8 9 10 11
The readdir method obviously uses an ArrayBuffer which then executes the callback function we defined - clearly manipulating the context we had expected.
So how can we manipulate this to use the this we expected?
The bind() method
this value and all the others can be used to pre-specify arguments to pass.
The bind method then creates a copy of the function.
1 2 3
In this example i set the
this keyword to
null as we don’t really need it and instead i passed a default argument to the console.log method.
To come back to our example we can also simply use it to set the this keyword to a value we want:
1 2 3 4 5
Well if we run the code again the error no more occurs but instead there is a new error:
1 2 3
The problem again is again that the
files array does not exist on the
this instance. Advanced methods like
Array.filter all accept a second argument which should be used as the
this value in the passed callback function.
1 2 3 4 5
Now our code actually does what it was supposed to do.