gpt4 book ai didi

javascript - 使用 Javascript 静态类和方法进行内存管理

转载 作者:行者123 更新时间:2023-11-29 15:56:26 25 4
gpt4 key购买 nike

我想知道这些东西是如何工作的。

class Test {
whatIsMyName(name) {
this.name = name;
}
tellMyName() {
return this.name;
}
}

let a = new Test();
a.whatIsMyName("Bob");
a.tellMyName(); // "Bob"

Browser assigns a part of memory to variable a.
Browser keeps the memory until I refresh the website.

class Test {
static whatIsMyName() {
const name = "Bob";
return name;
}
static tellMyName() {
return Test.whatIsMyName();
}
}

Test.whatIsMyName(); // "Bob"
Test.whatIsMyName(); // "Bob"
Test.tellMyName(); // "Bob"

Does browser assign another part of memory when I call it more than one?

最佳答案

Does browser assign another part of memory when I call it more than one?

很有可能,是的²。它必须分配字符串 "bob",并创建一个局部变量 name。两者都消耗内存。由于您既没有创建闭包也没有将字符串存储在某处,因此在每次这些调用之后,对它的所有引用都将丢失,因此垃圾收集可能会在之后直接释放内存。

² 现代 js 引擎做了很多聪明的优化,也许他们优化了一些东西......

关于javascript - 使用 Javascript 静态类和方法进行内存管理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57599615/

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