Let's assume I have an object:
function obj(){
this.getAll = function(){}
this.doSome = function(){}
}
If I want to invoke them, of course I need to do: obj.getAll();
Now, if I want this object to have a general method, but without specific name, like this code:
function obj(){
this.getAll = function(){}
this.doSome = function(){}
this.x = function(){}
}
And by invoking obj.abc(), it will go to this.x
Is it possible to do?
You can use Proxy (ECMAScript 2015) to do this:
var handler = {
get: function(target, name){
return name in target ? target[name] : target.x;
}
};
function obj() {
this.getAll = function() {
console.log('get all');
}
this.doSome = function() {
console.log('do some');
}
this.x = function() {
console.log('x');
}
}
var p = new Proxy(new obj(), handler);
p.getAll(); // get all
p.abc(); // x
NOTE: this is not currently supported by all environments. See compatibility table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With