-1

In this example. I need to update friends list from object function.

var MyClass = function () {
    this.friends = [];
    this.runtime = {
        add: function (name) {
            this.friends.push(name);
        }
    }
};

MyClass.prototype.AddFriend = function (name) {
    this.runtime.add(name);
};

MyClass.prototype.GetFriends = function () {
    return this.friends;
};

How it's possible?

Chandra Nakka
  • 14,022
  • 7
  • 31
  • 53

2 Answers2

1

Like I said in the comments, it makes much more sense to use this.friends.push(name), but if you really have to use that odd runtime function, then you need to save a copy of this to a new variable:

var MyClass = function () {
    var _this = this;
    this.friends = [];
    this.runtime = {
        add: function (name) {
            _this.friends.push(name);
        }
    }
};

DEMO

Andy
  • 39,764
  • 8
  • 53
  • 80
1

You could also use the bind() method:

var MyClass = function () {
    this.friends = [];
    this.runtime = {
        add: function (name) {
            this.friends.push(name);
        }.bind(this)
    }
};

MyClass.prototype.AddFriend = function (name) {
    this.runtime.add(name);
};

MyClass.prototype.GetFriends = function () {
    return this.friends;
};

Read more about it here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

  • No problem. Although as @Andy rightly pointed out you should actually be using this.friends.push(name)...but if you really can't avoid scoping your functions like that then it will do the job. – Peter Ringelmann Apr 07 '15 at 13:56