简体   繁体   中英

Is it possible to call a non-existent method on the fly and then create it?

The context of this question is as follows: I've written a jQuery plugin using jQuery's recommended design pattern where you pass a string as the first parameter of you plugin to call a desired (and pre-defined) method of that is an object of your plugin method. Such as:

$("selector").php('method_name');

With my particular plugin however (which just calls PHP functions through a simple AJAX handler), I would like to provide its users with the ability to call a given backend PHP function in this manner:

$("selector").php.strlen(param); // As an example of calling the PHP strlen function

Where .strlen isn't a defined method of the .php object (or any other object). In other words is there a way to prevent JavaScript from throwing an exception and catch the name of the desired method name a user is attempting to call, when that method in fact has not been defined and does not exist?

I don't want to go about defining the method names (or interfaces) to every PHP function for obvious reasons. It would be a lot of code overhead and would be very time consuming.

ECMAScript Harmony supports Proxies that let you intercept property access. Unfortunately, it's not widely supported yet (Firefox 18 supports it).

var php = new Proxy({}, {
    get: function (target, name) {
        return function () {
            var args = Array.prototype.slice.call(arguments);
            alert('Here you would call ' + name + '(' + args.join(', ') + ')');
        };
    }
});

php.strlen('hello');

There was something called __noSuchMethod__ , but again, it doesn't seem to be widely supported.

You could wrap it in a try catch block.

try {
   $("selector").php.strlen(param);
} catch(err) {
   // do sth
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM