methods - Javascript, Object prototype - avoid writing full path -


i know title may not clear, i'll try best explain i'm trying achieve.

i know modifying prototypes frowned upon, , reason, i'm trying figure out way without adding more 1 item prototype.

i know along lines of

object.prototype.collection = {}; object.prototype.collection.method1 = function(){ . . . }; object.prototype.collection.method2 = function(){ . . . }; object.prototype.collection.method3 = function(){ . . . }; etc. 

and whenever wanted use 1 of methods call

objectinstance.collection.method1(); 

the problem can pretty wordy , tedious, not mention if you're calling hundred methods collection, word 'collection' hundred times redundant , waste of bytes.

so hoping technique of creating methods in manner, without having write full path every time. i.e. write

objectinstance.method1(); 

and know right look.

my thought process @ point calling latter throw method not exist error. i'm curious if there manner of intercepting error?

for instance, in php there spl_autoload_register() function, called whenever class has not been defined, allowing whatever necessary load/define it. there equivalent strategy circumstance?

maybe add secondary 'fallback' method, so:

object.prototype.fallback = function( undefinedmethod ){      if(this.collection.undefinedmethod){          this.collection.undefinedmethod();      } }; 

and have called every time method undefined, passing in method.

any along these lines, or if it's possible, appreciated.

one of possible approaches use newly introduced proxy allows intercept arbitrary calls object members.

https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/proxy

an example mdn

var handler = {   get: function(target, name){     return name in target?         target[name] :         37;   } };  var p = new proxy({}, handler); p.a = 1; p.b = undefined;  console.log(p.a, p.b); // 1, undefined console.log('c' in p, p.c); // false, 37 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -