How to create a Javascript Hash Table / Associate Array Prototype -


with associative array such as:

var m = {}; m['a'] = {id:1, foo:'bar'}; m['b'] = {id:2, foo:'bar'}; 

is possible create prototype such as:

array.prototype.hello = function() { console.log('hello'); } m.hello(); 

this fails because m object, tired:

object.prototype.hello = function() { console.log('hello'); } 

and problematic too.

is possible create prototype can operate on data structure?


update: think need sleep :)

when create , use object.prototype.hello = function() { console.log('hello'); } works fine.

when add prototype , include 3rd party js framework, makes framework stop working.

you can assign custom properties object, , means can on object different immediate underlying prototype object.prototype. this, instance:

function mymap() { } mymap.prototype.hello = function() {     console.log('hello'); }; var m = new mymap(); m['a'] = {id:1, foo:'bar'}; m['b'] = {id:2, foo:'bar'}; m.hello(); 

note, though, if stored hello entry:

m['hello'] = {id:3, foo:'bar'}; 

...it hide hello object gets prototype.

also note m have properties not mymap.prototype, object.prototype (like {} does), tostring , valueof , hasownproperty. if want not have objectproperties, can that, too:

function mymap() { } mymap.prototype = object.create(null); mymap.prototype.hello = function() {     console.log('hello'); }; 

also note constructor functions (mymap, above) 1 way create objects underlying prototype. can use object.create directly:

var mapprototype = {     hello: function() {         console.log('hello');     } }; var m = object.create(mapprototype); 

Comments

Popular posts from this blog

node.js - Using Node without global install -

How to access a php class file from PHPFox framework into javascript code written in simple HTML file? -

java - Null response to php query in android, even though php works properly -