Chr*_*lip 6 javascript node.js express
我正在使用node.js/express堆栈开发一个网站,我正在尝试开发一种对我来说很新的功能风格.express方法res.send需要将函数作为方法调用,因为它this在正文中引用,但调用方法在函数样式中不能自然地工作.
您可以将该方法置于一个将其转换为函数的getter函数后面,但我不知道除了代码复杂性之外是否还有其他缺点?
例:
(function() {
"use strict";
function Foo() {
function bar() {
console.log(this.x);
}
return {
bar,
get baz() {
var s = this;
return () => s.bar();
}
}
}
var a = new Foo();
a.x = 5;
a.bar();
a.baz();
var b = a.bar;
var c = a.baz;
//b(); // throws an error because `this` is not defined
c();
function wrapper(f) {
f();
}
//wrapper(a.bar); // throws an error
wrapper(a.baz);
})();
Run Code Online (Sandbox Code Playgroud)
最终,这取决于您的具体用例,但添加包装函数在 javascript 和 Node 中非常典型,并且不太可能增加任何缺点。wrapper(a.bar); // throws an error您可以修复使用bind调用时看到的错误,如下所示:
wrapper(a.bar.bind(a));
调用bind将确保this稍后调用该函数时将其设置为适当的。
这是一个演示: https: //jsfiddle.net/zuL9g98m/
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |