如果我在构造函数中创建一个内部类,它是否会为我创建的外部类的每个实例分配内存?例如,
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);