Is this bad use of javascript prototype? -
i have javascript module creating menu objects designed this:
// original menu module function menu ( ) { alert ( "menu ( )"); } menu.prototype.init = function ( ) { alert ( "menu.init ( )"); } var menu = new menu;
i wish wrap inside api so
// new api containing menu ( function ( $api, window, undefined ) { $api.menu = function ( ) { alert ( "$api.menu ( )"); }; $api.menu.prototype.init = function ( ) { alert ( "$api.menu.init ( )"); }; }( window.$api = window.$api || {}, window )); var menu = new $api.menu;
it appears work question whether correct? eg end duplicating each prototype function each $api.menu instance?
i ask because i've used prototype first method , i'm unsure javascript doing under hood second example.
there isin't difference between both in terms of efficiency, difference namespacing constructor in second example, better practice polluting global namespace.
however following have been inefficient, since create new init
function everytime constructor getting called , not make use of prototype chain @ share functions between instances, resulting in higher memory usage.
function menu() { this.init = function () {}; }
Comments
Post a Comment