如何从open
函数访问原型的removeConnection()
数组?现在我在调用函数时得到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();
答案 0 :(得分:2)
对我而言,它会引发不同的错误Uncaught TypeError: open.filter is not a function
,修复方法是将this.open = open.filter
更改为this.open = this.open.filter
。
参见runnable示例:
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)
答案 1 :(得分:1)
您错过了this
。
Connections.prototype.removeConnection = function(res) {
this.open = this.open.filter(function(storedRes) {
if (storedRes !== res) {
return storedRes;
}
});
}