8

我想要做的是以下内容:

我有一个提醒某事的功能:

myfunction = function(foobar) { 
                 alert(foobar); 
             };

现在我想装饰它,这样:

decorate = function(callback) { 
              return function(foobar) { 
                  callback(foobar); 
                  console.log(foobar); 
           }; 
};

那么我可以写:

myfunction = decorate(myfunction);

然后 myfunction 将在控制台中进行正常的 + 登录。

我怎样才能使它与 Javascript 一起工作?

4

2 回答 2

10

是的你可以。事实上,你有,你的实现完美地工作:现场示例| 来源

var myfunction = function(foobar) { alert(foobar); };

var decorate = function(callback) { return function(foobar) { callback(foobar); console.log(foobar); }; };

var result = decorate(myfunction);

result("Hi there");

不过,我建议使用函数声明而不是函数表达式

function myfunction(foobar) {
    alert(foobar);
}

function decorate(callback) {
    return function(foobar) {
        callback(foobar);
        console.log(foobar);
    };
}

var result = decorate(myfunction);

result("Hi there");

如果您想创建更通用的版本,请查看使用apply( MDN | spec ) 和arguments伪数组 ( MDN | spec ):Live example | 来源

function decorate(original, wrapper, context) {
    return function() {
        try {
            original.apply(this, arguments);
        }
        catch (e) {
        }
        try {
            wrapper.apply(context || this, arguments);
        }
        catch (e) {
        }
    };
}

function myFunction(arg1, arg2) {
    alert("arg1 = " + arg1 + ", arg2 = " + arg2);
}

var newFunction = decorate(myFunction, function(arg1, arg2) {
    console.log("arg1 = " + arg1 + ", arg2 = " + arg2);
});

newFunction(1, 2);

该版本做了几件事:

  1. 允许您将回调作为参数提供给一个中心decorate函数。

  2. this让您有选择地提供调用回调时使用的“上下文”(值)。

  3. 保留this调用原始回调和(如果您不提供context)回调时的值。

...在装饰对象函数(有时称为方法)时很方便。

于 2012-05-03T15:58:00.443 回答
3

使用 arguments 和 apply 更通用:

function myfunction(foobar) { 
    alert(foobar); 
}

function decorate(callback) { 
    return function() { 
        callback.apply(null, arguments); 
        console.log(arguments); 
    }; 
}

var result = decorate(myfunction);

result("Hi there");
于 2012-05-03T16:10:57.577 回答