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());
1 Answer 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);