[英]Javascript - update parent object from child callback
I would like to set a property of a parent object every time a child object runs a callback function. 我想在子对象每次运行回调函数时设置父对象的属性。
I have the following code: 我有以下代码:
function Track(id) {
this.callback = function(args) {
this.name = args;
}
this.child = new objectName(this.callback, property);
this.name = this.child.name;
}
I want this.name
to be updated every time this.callback
is called...Is there any way to do this? 我希望每次调用
this.callback
都更新this.name
。有什么办法吗?
It's a typical scoping issue, this
will not reference to parent object when the callback is called. 这是一个典型的范围问题,在调用回调时,
this
不会引用父对象。
Try this instead: 尝试以下方法:
function Track(id) {
var that = this;
this.callback = function(args) {
that.name = args;
}
this.child = new objectName(this.callback, property);
this.name = this.child.name;
}
edit: see merlin's comment for a good explanation why this
can be a cause for problems. 编辑:请参阅merlin的注释,以很好地解释为什么
this
可能导致问题。 There might also be other possibilities to solve this, ie the usage of bind()
, but for that you'll have to pass the parent into the objectName contructor as well. 也可能有其他方法可以解决此问题,例如
bind()
的用法,但是为此,您还必须将父级传递给objectName构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.