dman
dman

Reputation: 11064

Access prototype value from prototype function

How do I access open array that is prototyped from removeConnection() function? Right now I get ReferenceError: open is not defined when I call the function.

function Connections() {}
Connections.prototype.open = [];

Object.defineProperty(Connections.prototype, 'total', {
  get: function total() {
    return this.open.length;
  }
});

Connections.prototype.removeConnection = function(res) {
  this.open = open.filter(function(storedRes) {
    if (storedRes !== res) {
      return storedRes;
    }
  });
}

var connections = new Connections();

Upvotes: 0

Views: 42

Answers (2)

Borys Serebrov
Borys Serebrov

Reputation: 16172

For me it raises a different error Uncaught TypeError: open.filter is not a function and the fix is to change this.open = open.filter to this.open = this.open.filter.

See the runnable example:

function Connections() {}
Connections.prototype.open = [];

Object.defineProperty(Connections.prototype, 'total', {
  get: function total() {
    return this.open.length;
  }
});

Connections.prototype.removeConnection = function(res) {
  this.open = this.open.filter(function(storedRes) {
    if (storedRes !== res) {
      return storedRes;
    }
  });
}

var connections = new Connections();

connections.open = ['one', 'two']
alert(connections.open)
connections.removeConnection('one')
alert(connections.open)

Upvotes: 2

Gregor Menih
Gregor Menih

Reputation: 5116

You're missing this.

Connections.prototype.removeConnection = function(res) {
  this.open = this.open.filter(function(storedRes) {
    if (storedRes !== res) {
      return storedRes;
    }
  });
}

Upvotes: 1

Related Questions