Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object unlimited methods by general [duplicate]

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?

like image 732
user3712353 Avatar asked Feb 13 '26 10:02

user3712353


1 Answers

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.

like image 125
madox2 Avatar answered Feb 15 '26 00:02

madox2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!