Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does .bind(this) pass by reference or by value?

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?

like image 350
hitecherik Avatar asked Apr 14 '18 18:04

hitecherik


People also ask

What is the difference between pass by reference and pass by value?

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.

What is pass by value in JavaScript?

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.

Does pass by value change the original value of a function?

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 .

Does Java pass objects by reference or 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?


2 Answers

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.

like image 68
Tomasz Mularczyk Avatar answered Sep 28 '22 05:09

Tomasz Mularczyk


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());
like image 35
ashfaq.p Avatar answered Sep 28 '22 06:09

ashfaq.p