Thursday, 15 April 2010

Pushing to a Javascript array that has a __proto__ -



Pushing to a Javascript array that has a __proto__ -

ok killing brain here have array

var myarray = ['bob', 'sue', 'jim']; myarray.__proto__ = new entity(); //entity looks entity = function(){ this.ischanged = false; this.add = function(newperson){ alert(this.length); //alerts 3 alert(json.stringify(this)); //alerts {} this.push(newperson); this.ischanged = true; } }

push not exist on object array per alert returning 3.

very curious how access array seems wrapped object proto

how access array seems wrapped object __proto__

it not wrapped - lost it's identity due modification of __proto__. array inherits new entity instance instead of array.prototype.

if want phone call array methods on it, have using .call:

array.prototype.push.call(this, newperson);

however, implementation of inheritance questionable anyway. if utilize array object , mutate [[prototype]], rather should doing

var myarray = new entitiy(['bob', 'sue', 'jim']); // entity looks function entity(arr) { if (!array.isarray(arr)) { arr = []; // maybe: // arr.push.apply(arr, arguments); } arr.__proto__ = entity.prototype; arr.ischanged = false; homecoming arr; } entity.prototype = object.create(array.prototype); entity.prototype.constructor = entity; entity.prototype.add = function(newperson) { alert(this.length); //alerts 3 alert(json.stringify(this)); //alerts ["bob","sue","jim"] this.push(newperson); this.ischanged = true; };

javascript arrays

No comments:

Post a Comment