Is there any way to call an action when the method does not exist in an object in javascript?

2

In PHP, we have some special methods that can be included in a class.

One of them is __call , which causes an action to be invoked (through it) when a method does not exist in a class.

Example:

class Exemplo
{
    public function existe()
    {
        echo 'Eu existo';
    }

   public function __call($method, $parameters)
   {
       echo "$method não existe, mas vou fazer alguma coisa legal";
   }
}

$e = new Exemplo;

$e->existo(); // 'Eu existo'

$e->nao_existo(); // "nao_existo não existe, mas vou fazer alguma coisa legal"

Is there any way to do this in javascript?

Example:

function special(){}

special.prototype.existe = function () {
     console.log('Esse método existe');
}
    
asked by anonymous 02.10.2015 / 16:20

2 answers

5

There is no implementation that is broadly supported equivalent to the PHP _call function in JavaScript.

In ECMAScript 2015 (ES6), there is a new implementation that will allow something like __call, the Proxy . However, not all browsers have already implemented this object. At the moment, only Firefox and Edge support Proxy.

According to the Mozilla example, it is used this way:

var handler = {
    get: function(target, name){
        return name in target?
            target[name] :
            37;
    }
};

var p = new Proxy({}, handler);
p.a = 1;
p.b = undefined;

console.log(p.a, p.b); // 1, undefined
console.log('c' in p, p.c); // false, 37

Firefox supported a nonstandard function that allowed this. However, since version 39, it is no longer supported. See Object.prototype .__ noSuchMethod__

var obj = {};
obj .__noSuchMethod__ = function (name, args) {
    alert(name);
    alert(args);
}

obj.teste("teste1");
    
02.10.2015 / 16:31
2

Invoking functions in Types that are not functions generates an error in JavaScript.

In other words, using () at the end of a variable or property other than a function gives an error and there is no tool like PHP has.

How to get around this?

Well, this will have to be done in the code, preventing errors.

You can check whether the variable or property is a function:

function foo(){
    // fazer algo
}

if (typeof foo === "function") foo();

Use a method to run functions. At the bottom there is already .call or .apply , but you can create your own too:

function corredor(fn, argumentos, fallback) {
    var func = typeof fn === "function" ? fn : fallback;
    return func.apply(this, argumentos);
}

var foo = 'string';
var retorno = corredor(foo, [1, 2, 3], function () {
    return [].reduce.call(arguments, function (a, b) {
        return a + b;
    });
});
console.log(retorno);

jsFiddle: link

    
02.10.2015 / 16:45