javascript - 是否可以将非共享变量添加到原型(prototype)中?

标签 javascript

我正在构建一个函数,可以用一些常用函数改造我的一些原型(prototype)。

我还想通过这个机制添加对象实例特定的变量,有点像:

function give_weird_container(target) {
    target.<somehow instance specific, not prototype>.underlying_container = [];
    target.prototype.container_func = function(x, y, z) {
        return this.underlying_container[x + 2*y + 3*z];
    }
}

function my_class1() {}

give_weird_container(my_class1);

现在当我创建一个新的 my_class1 实例时,它应该有一个属性“uderlying_container”,就像我调用一样

this.underlying_container = [];

在构造函数中。

在 give_weird_container 函数的范围内,这是否可能?

最佳答案

Is it possible to add a not shared variable to a prototype?

没有。原型(prototype)上的所有属性都是共享的。实例特定属性只能在实例创建后设置。

但是,您可以向原型(prototype)添加一个getter,如果它不存在,它将创建一个特定于实例的属性。

例如:

Object.defineProperty(target.prototype, 'underlying_container', {
  get: function() {
    if (!this._underlying_container) {
      this._underlying_container = [];
    }
    return this._underlying_container;
  },
});

getter 是共享的,但返回的值是每个实例。

如果您不喜欢每次访问 this.underlying_container 时都会执行 getter,您可以在第一次调用原型(prototype)属性时将其替换为实例属性:

Object.defineProperty(target.prototype, 'underlying_container', {
  get: function() {
    Object.defineProperty(this, 'underlying_container', {value: []});
    return this. underlying_container;
  },
});

Object.defineProperty(this, 'underlying_container', {value: []}); 将在实例 上创建一个同名的新属性,从而隐藏getter 在原型(prototype)上定义。


采纳@4caSTLe 的建议,如果可以直接改变实例,那么你可以做类似这样的事情,这有点不那么“神奇”:

var give_weird_container = (function() {
    function container_func(x, y, z) {
        return this.underlying_container[x + 2*y + 3*z];
    };

    return function(target) {
      target.underlying_container = [];
      target.container_func = container_func;
    };
}());

function my_class1() {}

var instance = new my_class1();

give_weird_container(instance);

关于javascript - 是否可以将非共享变量添加到原型(prototype)中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41149199/

相关文章:

javascript - 用于可配置依赖注入(inject)的 RequireJS 依赖覆盖

javascript - 使用 javascript,客户端打开文件

javascript - 使用 lua.vm.js 在 javascript 中迭代 Lua 表

javascript - 使用 Vue.js 和 vue-router 构建 SPA 时如何销毁组件?

javascript - listjs分页下拉显示全部

javascript - <ul> 导航栏中的 JS/CSS 下拉菜单

javascript - 使用变量作为对象的属性,如何?

javascript - 具有大数据库的 AngularJS 搜索

javascript - 动态创建 DIV,不是动态获取高度和宽度

javascript - 为什么状态不在计算中更新?