gpt4 book ai didi

javascript - 从原型(prototype)函数访问原型(prototype)值

转载 作者:行者123 更新时间:2023-11-28 18:45:21 25 4
gpt4 key购买 nike

如何访问从 removeConnection() 函数原型(prototype)化的 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)

关于javascript - 从原型(prototype)函数访问原型(prototype)值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35419330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com