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}
?我认为对象是通过引用传递的?
答案 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}