I create a function somewhere and I bind it to this
so that I can use the parent block's meaning of this
as the value of this
within the function. For example:
var foo = function() {
// some stuff involving other stuff
}.bind(this);
Is the this
I pass as an argument to bind
passed by reference, or by value? So if I change the parameters of the this
object a bit later in the outer block of code, and afterwards call foo
, will foo
use the value of this
at the time I called bind
, or at the time I called foo
?
To summarise, in pass by reference the function and the caller use the same variable and object. In pass by value the function is provided with a copy of the argument object passed to it by the caller. That means the original object stays intact and all changes made are to a copy of the same and stored at different memory locations.
In simple language, we can understand it as, in a pass by value, the function receives a copy of the variable, which is independent of the originally passed variable. Pass by value in JavaScript requires more space as the functions get a copy of the actual content therefore a new variable is created in the memory.
So any changes made inside the function does not affect the original value. In Pass by value, parameters passed as an arguments create its own copy. So any changes made inside the function is made to the copied value not to the original value .
Answer: Java supports pass by value but when we are dealing with objects such as Java array objects, then the object reference is passed to the method. Q #3) Does Java pass objects by reference or value?
So if I change the parameters of the this object a bit later in the outer block of code, and afterwards call foo, will foo use the value of this at the time I called bind, or at the time I called foo?
at the time you called foo.
this
is a reference to Object. That means Object may get mutated at some point and you will get "fresh - up to date" values of it.
If you will change the value of this
object, then foo will get the fresh value of this
at the time foo
is called.
var module = {
x: 42,
getX: function () {
return this.x;
}
}
var retrieveX = module.getX;
console.log(retrieveX()); // The function gets invoked at the global scope
// expected output: undefined
var boundGetX = retrieveX.bind(module);
module.x = 52;
console.log(boundGetX());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With