javascript - 推送到具有 __proto__ 的 Javascript 数组

标签 javascript arrays

好吧,我正在绞尽脑汁,我有一个数组

var myArray = ['Bob', 'Sue', 'Jim'];
myArray.__proto__ = new Entity();

//Entity looks something like this
Entity = function(){
   this.isChanged = false;
   this.add = function(newPerson){
      alert(this.length); //alerts with 3
      alert(JSON.stringify(this)); //alerts a {}
      this.push(newPerson); 
      this.isChanged = true;

  }
}

推送不存在于对象上,但根据返回 3 的警报,它显然是一个数组。

非常好奇如何访问我的数组,由于我的proto

,它似乎被一个对象包裹着

最佳答案

how to access my array that seems to be wrapped by an object thanks to my __proto__

它没有被包装——它只是因为你修改了 __proto__ 而失去了它的身份。该数组现在继承您的新实体实例,而不是Array.prototype

如果您想对其调用Array 方法,您必须使用.call 来完成。 :

Array.prototype.push.call(this, newPerson);

但是,无论如何,您对继承的实现是有问题的。即使您使用数组对象和 mutate its [[prototype]] ,你更应该做

var myArray = new Entitiy(['Bob', 'Sue', 'Jim']);

// Entity looks like this
function Entity(arr) {
    if (!Array.isArray(arr)) {
        arr = [];
        // maybe:
        // arr.push.apply(arr, arguments);
    }
    arr.__proto__ = Entity.prototype;
    arr.isChanged = false;
    return arr;
}
Entity.prototype = Object.create(Array.prototype);
Entity.prototype.constructor = Entity;
Entity.prototype.add = function(newPerson) {
    alert(this.length); //alerts with 3
    alert(JSON.stringify(this)); //alerts a ["Bob","Sue","Jim"]
    this.push(newPerson);
    this.isChanged = true;
};

关于javascript - 推送到具有 __proto__ 的 Javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26439799/

相关文章:

python - 使用 np.savez 存储字典会产生意想不到的结果?

c - 当您写入内存超出数组范围时会发生什么?

javascript - 如何更换 Cordova 主页?

javascript - 将 snap.js 应用到我的主要内容包装器似乎破坏了我的一些 jQuery 函数

javascript - Node-RED:您可以从功能 Node 中的本地存储读取数据吗?

javascript - OpenLayers map 事件无法调用方法

javascript - 创建公共(public)变量Nodejs

c++ - 将 C++ 数组转换为 vector

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c++ - 未解析的外部符号 - 如何修复?