好吧,我正在绞尽脑汁,我有一个数组
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/