2010-10-04 18 views
5

Có cách nào để chỉ định một cái gì đó tương tự như sau trong javascript?Javascript Metaprogramming

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 

Trả lời

6

Không, không thực sự. Có một số lựa chọn thay thế - mặc dù không đẹp hay tiện lợi như ví dụ của bạn.

Ví dụ:

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

số

0

Gần 6 năm sau và có cuối cùng một cách, sử dụng Proxy:

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();