绑定函数不返回对象的引用

时间:2018-02-09 01:49:14

标签: javascript function bind pass-by-reference partial-application

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}

有人可以解释为什么对cat的调用不会返回{x:3, y:4}?我认为对象是通过引用传递的?

2 个答案:

答案 0 :(得分:1)

Javascript不是通过引用传递的(对象引用是按值传递的),这就是为什么你不希望发生的事情,看看here

答案 1 :(得分:0)

在您的代码中,someArgs = {x:3, y:4}创建新对象,而不是建议的方式

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}

建议方式:

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}