小编Chr*_*lip的帖子

Getters背后的封装方法

我正在使用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.js express

6
推荐指数
1
解决办法
59
查看次数

标签 统计

express ×1

javascript ×1

node.js ×1