python decorator with javascript

python decorator with javascript

本文关键字:javascript with decorator python      更新时间:2023-09-26

我想做的是:

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

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

现在我想装饰它,以便:

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

所以我可以写:

myfunction = decorate(myfunction);

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

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

是的,你可以。事实上,你有,你的实现工作得很好:现场示例 |源

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): 实时示例 | source

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. 调用原始回调和(如果未提供context)回调时保留this的值。

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

使用参数和应用更通用:

function myfunction(foobar) { 
    alert(foobar); 
}
function decorate(callback) { 
    return function() { 
        callback.apply(null, arguments); 
        console.log(arguments); 
    }; 
}
var result = decorate(myfunction);
result("Hi there");