【发布时间】:2013-05-13 01:14:12
【问题描述】:
我确定这一定存在于某个地方,但我一直无法找到它...
我正在尝试编写一个将对象作为参数并更新其引用的函数。不是引用的属性,也不是重新分配对象,而是更新整个引用。
请注意,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”?
【问题讨论】:
-
有关如何在 js 中传递参数的详细说明,请参阅我对这个相关问题的回答:stackoverflow.com/questions/13506398/…
标签: javascript object