从原型功能访问原型值

Access prototype value from prototype function

本文关键字:原型 访问 功能      更新时间:2023-09-26
如何

访问从removeConnection()函数原型open数组?现在,当我调用该函数时,我会ReferenceError: open is not defined

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();
对我来说,

它引发了一个不同的错误Uncaught TypeError: open.filter is not a function,解决方法是将this.open = open.filter更改为this.open = this.open.filter

请参阅可运行的示例:

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)

你错过了this .

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