1

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?

blisstdev
  • 633
  • 4
  • 13

1 Answers1

0

It's a typical scoping issue, this will not reference to parent object when the callback is called.

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. There might also be other possibilities to solve this, i.e. the usage of bind(), but for that you'll have to pass the parent into the objectName contructor as well.

Kevin Sandow
  • 4,003
  • 1
  • 20
  • 33
  • The explanation is not correct. What `this` points to will depends on how `objectName` calls it.See [this question](http://stackoverflow.com/questions/15498508/unable-to-access-the-object-using-this-this-points-to-window-object) – merlin Jun 17 '14 at 09:43
  • `this` is hardly ever a reference to a function. – Bergi Jun 17 '14 at 10:03
  • perfect thanks all! Kevin's answer worked perfectly and merlin's pointer to the other question was an enlightening explanation. all around great answers. – blisstdev Jun 17 '14 at 16:50