0

I have been trying to figure out how can a method of an object be passed by value to a global variable but have been unable to do so. I have passed an object method to unboundGetX (it should be passed by reference) but after changing the object method later after assignment, the value stored inside variable doesn't change.

So are methods of object passed by value and not by reference?

Please help me on this.

const module = {
 x: 42,
 getX: function() {
 console.log(this);
 return this.x;
 }
};
 
let unboundGetX = module.getX;
module.getX = function () {
 console.log("hello");
 return 10;
}
console.log(module.getX());
console.log(unboundGetX());

asked Aug 30, 2021 at 0:13

1 Answer 1

1

One way of thinking about variables (all variables) is that they contain pointers to things in memory. With this:

const module = {
 x: 42,
 getX: function() {
 console.log(this);
 return this.x;
 }
};
let unboundGetX = module.getX;

unboundGetX now points to the same function in memory that module.getX points to.

If you reassign:

module.getX = function () {

module.getX now points to a different function (one that was just created), while unboundGetX keeps pointing to the original function.

The exact same behavior occurs if getX is a primitive, not a function (which might make it easier to understand the concept initially).

const module = {
 getX: 'foo'
};
 
const foo = module.getX;
module.getX = 'bar';
console.log(module.getX);
console.log(foo);

answered Aug 30, 2021 at 0:18
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.