gpt4 book ai didi

javascript - ES6 中的内部类占用更多内存?

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

如果我在构造函数中创建一个内部类,它是否会为我创建的外部类的每个实例分配内存?例如,

class PriorityQueue {
constructor(maxSize) {
// Set default max size if not provided
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize;

// Init an array that'll contain the queue values.
this.container = [];

// Create an inner class that we'll use to create new nodes in the queue
// Each element has some data and a priority
this.Element = class {
constructor(data, priority) {
this.data = data;
this.priority = priority;
}
};
}
}

是否为 Priority Queue 类的每个实例创建了 Element 类?有没有办法让这个类静态化?

最佳答案

因为您正在构造函数中创建类并将其分配给 this.Element,并且每次实例化 PriorityQueue 时构造函数都会运行 - 是的,您正在创建新的Class 用于每个实例。如果您只想为所有实例化一个类,请将其放在原型(prototype)上:

class PriorityQueue {
constructor(maxSize) {
// Set default max size if not provided
if (isNaN(maxSize)) {
maxSize = 10;
}
this.maxSize = maxSize;

// Init an array that'll contain the queue values.
this.container = [];
}
}
PriorityQueue.prototype.Element = class {
constructor(data, priority) {
this.data = data;
this.priority = priority;
}
}

const p1 = new PriorityQueue(1);
const p2 = new PriorityQueue(2);
console.log(p1.Element === p2.Element);

关于javascript - ES6 中的内部类占用更多内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50085472/

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