简体   繁体   English

Javascript,groovy喜欢invoke方法吗?

[英]Javascript, groovy like invoke method?

I was wondering if there is a way having for instance: 我想知道是否有办法例如:

var klass = {

   getName : function () { return "myname"; }

}

and doing klass.getName(); 并做klass.getName();

having a method fire before getName is actually called? 在实际调用getName之前有方法触发? In Groovy all method calls can for instance be listened to if an invoke method is added: 在Groovy中,例如,如果添加了invoke方法,则可以侦听所有方法调用:

var klass = {

   invoke function() { console.log("fires before getName()") ; },
   getName : function () { return "myname"; }

}

I know this a long shot, but worth a try. 我知道这很远,但是值得一试。

Not interested in altering the way the method is actually invoked: klass.getName() 对更改实际调用方法的方式不感兴趣: klass.getName()

The obvious answer is to simply call invoke in your getName method. 显而易见的答案是简单地在getName方法中调用invoke If, for whatever reason, you don't wanna do that, you can proxy the methods of klass afterwards: 如果出于某种原因您不想这样做,则可以在以后代理klass的方法:

// loop through all properties of klass
for (var i in klass) {
    // skip if it's not a custom property, not a function or the invoke function
    // (to prevent infinite nested calls)
    if(!klass.hasOwnProperty(i) || typeof klass[i] !== 'function' 
            || i === 'invoke') {
        continue;
    }

    // add the invoke() method as a proxy to the current method
    var old = klass[i];
    klass[i] = function () {
        klass.invoke.apply(this, arguments);
        return old.apply(this, arguments);
    };
}

You can also put everything together neatly like this: 您还可以像这样将所有内容整齐地组合在一起:

var klass = (function () {
    this.invoke = function () {
        console.log('called invoke()');
    };

    this.getName = function () {
        return "called getName()";
    };

    (function (_this) {
        for (var i in _this) {
            if (!_this.hasOwnProperty(i) || typeof _this[i] !== 'function' 
                    || i === 'invoke') {
                continue;
            }

            var old = _this[i];
            _this[i] = function () {
                _this.invoke.apply(_this, arguments);
                return old.apply(_this, arguments);
            };
        }
    })(this);

    return this;
})();

console.log(klass.getName());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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