Может быть не так удобно, но вы также можете использовать прокси-сервер:
function wrapped() {};
const testFunc = new Proxy(wrapped, {
maxInstances: 3,
instances: 0,
construct: function (target, argumentsList, newTarget) {
if (this.instances >= this.maxInstances) {
throw new Error('Ran out of instances...');
}
this.instances++;
return new wrapped();
}
});
new testFunc();
new testFunc();
new testFunc();
new testFunc(); // throws
прокси может быть возвращена, например, allowMaxInstances
Функция, которая позволит повторно использовать этот шаблон.
Или вы можете использовать шаблон Singleton (по аналогии с ответом @melpomene):
const TestFunc = (function() {
const maxInstances = 3;
let instances;
function createInstance() {
const object = new Object('I am new...');
return object;
}
return {
getInstance: function() {
if (instances < maxInstances) {
return createInstance();
}
throw new Error('Run out of instances...');
}
};
})();
TestFunc.getInstance();
TestFunc.getInstance();
TestFunc.getInstance();
TestFunc.getInstance(); // throws
В чем причина этого? Почему вы хотите ограничить? – Joseph
@JosephtheDreamer Изучение Javascript. Так что старайтесь все возможности, которые приходят на ум. Нет бизнес-причины. –