我正在使用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)