2010-10-04 15 views
5

Javascript'te aşağıdakine benzer bir şey belirtmenin bir yolu var mı?Javascript Meta Programlama

var c = {}; 
c.a = function() { } 

c.__call__ = function (function_name, args) { 
    c[function_name] = function() { }; //it doesn't have to capture c... we can also have the obj passed in 
    return c[function_name](args); 
} 

c.a(); //calls c.a() directly 
c.b(); //goes into c.__call__ because c.b() doesn't exist 

cevap

6

Hayır, pek değil. Bazı alternatifler vardır - örneğiniz kadar hoş ya da kullanışlı olmasa da. Proxy kullanarak

function MethodManager(object) { 
    var methods = {}; 

    this.defineMethod = function (methodName, func) { 
     methods[methodName] = func; 
    }; 

    this.call = function (methodName, args, thisp) { 
     var method = methods[methodName] = methods[methodName] || function() {}; 
     return methods[methodName].apply(thisp || object, args); 
    }; 
} 

var obj = new MethodManager({}); 
obj.defineMethod('hello', function (name) { console.log("hello " + name); }); 
obj.call('hello', ['world']); 
// "hello world" 
obj.call('dne'); 
1

sayılı

0

Neredeyse 6 yıl sonra ve bir yol nihayet, orada:

Örneğin

let c = {}; 
 

 
c.a = function() { document.write('<pre>invoked \'a\'</pre>'); }; 
 

 
let p = new Proxy(c, { 
 
    get(target, key) { 
 
    if (!(key in target)) { 
 
     return function() { document.write(`<pre>invoked '${key}' from proxy</pre>`); }; 
 
    } 
 
    
 
    return target[key]; 
 
    } 
 
}); 
 

 
p.a(); 
 
p.b();