javascript - 经典继承和对象池

标签 javascript

我目前正在从事一个使用以下继承结构的项目:

var Type = function(a){
  this.a = a;
};

var SubType = function(a){
  Type.call(this, a);
};
SubType.prototype = Object.create(Type.prototype);
SubType.prototype.constructor = SubType;

现在,我正在尝试在等式中添加一些对象池。我目前使用的模式类似于(伪代码):

Type.new = function(){
  if object available in pool
    reset popped pool object 
    return pool object
  else
    return new Type()
}
var a = Type.new();

当然,使用这两种模式的问题是对 SubType 的构造函数调用不会从 Type 的池中提取。有没有办法在不转移到工厂结构的情况下解决这个问题? IE。有没有办法在构造函数中按照以下方式做一些事情:

var SubType = function(){
  build on top of instanceReturnedFromFunction()
};

知道它在上下文中并不总是一致的,我还想保留继承结构,以便 instanceof 等仍然有效:

最佳答案

The problem with using this pattern is that constructor calls on SubType wont draw from Type's pool

其实那不是问题,那是必须的。 TypeSubType 实例确实有不同的原型(prototype),您不能互换使用它们(和 swapping prototypes doesn't work either )。
您肯定需要为所有类(class)设置单独的池。您可以毫无问题地使用 .new 工厂方法 - 尽管您当然应该以编程方式创建这些工厂:

function pooledNew() {
    // `this` is the "class" constructor function
    if (!this.pool) this.pool = [];
    var instance = this.pool.length ? this.pool.pop() : Object.create(this.prototype);
    this.apply(instance, arguments); // reset / initialise
    return instance;
}
function makePooling(constr) {
    constr.new = pooledNew;
    constr.pool = [];
    var proto = constr.prototype;
    if (proto.constructor !== constr)
        proto.constructor = constr;
    if (typeof proto.destroy != "function")
        proto.destroy = function destroyInstance() {
            this.constructor.pool.push(this);
        };
    return constr;
}

这些设计用于完美地处理子类,在您的示例中就是这样

makePooling(Type);
makePooling(SubType);

在 ES6 中,子类甚至会从它们的父类(super class)构造函数中继承 new 方法。

class Type {
    constructor(a) {
        this.a = a;
    }
    destroy() { // overwriting default behaviour
        this.a = null; // for GC
        this.constructor.pool.push(this);
    }
}
makePooling(Type);

class SubType extends Type {
    // you can use super calls in both "constructor" and "destroy" methods
}

关于javascript - 经典继承和对象池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31369202/

相关文章:

javascript - 使用 ASP.NET WCF 服务 JSON 发布数据

javascript - 播放视频元素不流畅

javascript - 从 1 到 10 中随机挑选数字而不重复一个的最佳方法是什么?

javascript - Ajax 请求后 Alexa Skill 没有响应

javascript - 什么是 Angular 或 JavaScript 中注释中的 @license 和 @publicApi

javascript - JsTestDriver,测试函数的名称

javascript - this 关键字在链方法上的用法 - JavaScript

javascript - Twilio 聊天演示 js 问题

javascript - 使 div 元素粘在屏幕顶部

javascript - 无法让 2 人井字棋游戏运行 JavaScript