我确定这一定存在于某个地方,但我一直无法找到它......
我正在尝试编写一个将对象作为参数并更新其引用的函数。不是引用的属性,也不是重新分配对象,而是更新整个引用。
请注意,PubSub 只是为了证明传入和更新的对象类型需要异步性和灵活性。
最好用例子来解释:
//ideally how function would work
function watch(event, obj) {
PubSub.on(event, function(model) {
// I want to update the entire object
// I understand that currently, this is just reassigning
// I know I can do obj.prop = model, but that's not what I want to do
obj = model;
}
};
//example usage
var myObj = {"name" : "Tom"};
watch("anEvent", myObj);
console.log(myObj.name); //still "Tom"
// time passes, then somewhere
PubSub.trigger("anEvent", {"name" : "John"})
console.log(myObj.name); // now should read "John"
这是一种bind()
方法(例如$.bind()
,currying)有用的场景,还是仅用于在适当的上下文中使用“this”?