Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript-从子回调更新父对象_Javascript_Callback_Parent Child - Fatal编程技术网

Javascript-从子回调更新父对象

Javascript-从子回调更新父对象,javascript,callback,parent-child,Javascript,Callback,Parent Child,我想在每次子对象运行回调函数时设置父对象的属性 我有以下代码: function Track(id) { this.callback = function(args) { this.name = args; } this.child = new objectName(this.callback, property); this.name = this.child.name; } 我希望每次调用this.callback时都更新this.name

我想在每次子对象运行回调函数时设置父对象的属性

我有以下代码:

function Track(id) {
    this.callback = function(args) {
        this.name = args;
    }

    this.child = new objectName(this.callback, property);
    this.name = this.child.name;
}

我希望每次调用this.callback时都更新this.name…有什么方法可以做到这一点吗?

这是一个典型的作用域问题,调用回调时不会引用父对象

请尝试以下方法:

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;
}

编辑:请参阅merlin的评论,了解为什么这会导致问题。也可能有其他的解决方法,即使用bind,但为此,您还必须将父对象传递给objectName构造函数。

解释不正确。这所指向的将取决于objectName如何调用它。请看,这几乎不是对函数的引用。非常感谢!凯文的回答非常有效,梅林指出的另一个问题是一个启发性的解释。都是很好的答案。