0
let someArgs = {x:1, y:2}
let dog = args => {return args}
let cat = dog.bind(null, someArgs)
someArgs = {x:3, y: 4}
cat() // {x:1, y:2}

Can someone explain why the call to cat does not return {x:3, y:4}? I thought objects were passed by reference?

user2535381
  • 588
  • 1
  • 7
  • 10
  • 1
    you are replacing the `someArgs` object with a new object, but the original object is bound as the first argument to `cat` - but this is a different object ... there's a difference between replacing an object and changing an objects content – Jaromanda X Feb 09 '18 at 01:53

2 Answers2

1

Javascript is not pass by reference (Object reference is passed by value), That's why what you expect do not happen, Take a look here

Skyler
  • 656
  • 5
  • 14
  • Aha. So `someArgs` passed into bind would refer to some section in memory and the function would be operating with that section in memory. Later when I set `someArgs = {x:3, y:4}` it is creating a new section in memory and assigning those values to it, not affecting the old section in memory (which the function references). Does that sound about right? – user2535381 Feb 09 '18 at 03:36
  • Also, when `let cat = dog.bind(null, someArgs)` is replaced with `let cat = () => dog(someArgs)` `{x:3, y:4}` is returned. Why should this work any differently than the bind case? – user2535381 Feb 09 '18 at 04:00
  • 1
    in `let cat = dog.bind(null, someArgs)` value of someArgs (that is a reference to the object) is copied and then it is used during `cat()`. But in `let cat = () => dog(someArgs) {x:3, y:4}` you just declare function cat (no execution), during the execution only `someArgs` value is considered. So it gets the latest value. – Skyler Feb 09 '18 at 05:49
  • 1
    @user2535381: the difference is the time at which the variable `someArgs` is resolved. Variables inside a function are resolved only when the function is called. At the moment the arrow function is called, `someArgs` refers to the new object. With `.bind`, the variable is resolved when you call bind, not when the function returned by bind is called. At the moment bind is called, `someArgs` still has the old value. – Felix Kling Feb 09 '18 at 07:28
0

In your code, someArgs = {x:3, y:4} creates new object, instead do the suggested way

let someArgs = {x:1, y:2}
let dog = args => {return args}
let cat = dog.bind(null, someArgs)
someArgs = {x:3, y: 4}
cat() // {x:1, y:2}

Suggested way:

let someArgs = {x:1, y:2}
let dog = args => {return args}
let cat = dog.bind(null, someArgs)
someArgs.x = 3;
someArgs.y = 4;
cat() // {x:1, y:2}
Tilak Putta
  • 758
  • 4
  • 18