3

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?

user3712353
  • 3,931
  • 4
  • 19
  • 33

2 Answers2

1

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.

madox2
  • 49,493
  • 17
  • 99
  • 99
0

You are assuming your obj is an object, but you are coding it like a function.

It should be like

var obj = {
    this.getAll = function(){}
    this.doSome = function(){}
    this.x = function(){}
};

And answering to your question, you cannot invoke a method that was not defined, because JavaScript will return you 'undefined' as the method does not exist.

Khalav
  • 77
  • 7