gpt4 book ai didi

javascript - 使用原型(prototype)函数作为事件处理程序会导致内存泄漏吗?

转载 作者:行者123 更新时间:2023-12-03 02:03:07 24 4
gpt4 key购买 nike

var foo = function () {
}

foo.prototype.bar = function () {
}

var test = function () {
var socket = new WebSocket("ws://localhost");
socket.onopen = foo.prototype.bar;
//Or socket.addEventListener('open', foo.prototype.bar)
}

test();

socket 应在测试执行后立即接受 GC。但它有一个 onopen 处理程序,并且保存对套接字对象的引用。

由于该函数是在原型(prototype)上定义的,因此它将永远存在(我认为)。问题是该函数是否会阻止套接字被垃圾回收。

即打开事件后是否需要取消订阅以防止内存泄漏?

最佳答案

Since the function is defined on the prototype so it will live forever (I think).

是的。

The question is will that function prevent socket from getting GCed?

没有。套接字对象正在引用该函数,而不是相反。

socket should be subject to GC right after test is executed.

是的,socket 变量是,但是您创建的套接字对象(其中包含对处理程序的引用)仍然存在 - 它由从网络接收有效负载的内部监听器引用。

Do I need to unsubscribe to the open event after its opened to prevent memory leak?

没有。仅当您想要保持套接字打开但停止监听时,才需要取消订阅。

但是,完成测试后,您需要关闭套接字!

关于javascript - 使用原型(prototype)函数作为事件处理程序会导致内存泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49929326/

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