python decorator with javascript
python decorator with javascript
我想做的是:
我有一个提醒某事的功能:
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);
该版本做了几件事:
允许您将回调作为参数提供给一个中央
decorate
函数。允许您选择提供调用回调时要使用的"上下文"(
this
值)。
在调用原始回调和(如果未提供
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");
相关文章:
- Modify Javascript with C#
- JavaScript with PHP SESSION
- Javascript with IE 11 issue
- javascript with()函数获胜'我不适合歌剧、Chrome或Brave
- Javascript with Heroku
- sqlite with javascript with phonegap using build.phonegap.co
- Including html+javascript with javascript
- .post javascript with PHP 以启用 select 语句返回
- Scrape query JavaScript with scrapy
- 正则表达式 JavaScript with punct,space 和 alnum
- writing JavaScript with PHP
- 将字符串从 C# 传递到 Javascript with Phonegap 和 Windows Phone 8
- Javascript with SJCL lib,在 GCM 模式下解密 AES
- Javascript with jquery datepicker using knockout
- Java to JavaScript with NodeJS convertion
- onMouseOver JavaScript with CSS list-style-image
- Appending on javascript with onclick
- javascript with html for stickynotes
- Scraping javascript with R
- Inserting javascript with jQuery .html