猫鼬和箭头函数

Cod*_*XYZ 6 mongoose node.js

我希望能消除我关于箭头函数和词法 this 的一些困惑,我的 mongoose 用例。

向 mongoose Schema 添加方法时,不能使用箭头函数。根据这篇文章:https : //hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4 “词法范围只是意味着它从包含箭头函数的代码中使用它。”

因此,如果我在 mongoose 方法中使用箭头函数,为什么 'this' 不指模式对象,而 pre-es6 函数呢?如果模式和箭头函数在同一个文件中,词法范围是否不绑定到模式?

谢谢!

UserSchema.methods.toJSON = function() {
  const user = this;
  const userObject = user.toObject();
  return _.pick(userObject, ['_id', 'email']);
};
Run Code Online (Sandbox Code Playgroud)

vp_*_*rth 5

词法作用域只是意味着它从包含箭头函数的代码中使用它。

我只是演示一下:

window.answer = 'Unknown'; // `this` equals to `window` in browser (no strict mode)
const object = {
  answer: 42,
  arrow: () => this.answer,
  wrap() {
    const arrow = () => this.answer;
    return arrow();
  },
  stillOuter() { return this.arrow();},
  method() {return this.answer;},
  likeArrow: function() {return this.answer;}.bind(this)
};

console.log(object.arrow(), object.stillOuter(), object.likeArrow()); // Unknown Unknown 
console.log(object.method(), object.wrap()); // 42 42
Run Code Online (Sandbox Code Playgroud)

箭头函数this只属于外部上下文。

因此,如果您的箭头函数将在正确的对象内部声明,this那么它也将是正确的(几乎)。
查看该解决方法:

let tmp = Symbol(); // just to not interfere with something
UserSchema.methods[tmp] = function() {
  this.toJson = data => JSON.stringify(data);
  // All arrow functions here point into `UserSchema.methods` object
  // It will be still `UserSchema.methods` if implementation will copy these methods into other objects or call in the other context
};
UserSchema.methods[tmp]();
delete UserSchema.methods[tmp];
Run Code Online (Sandbox Code Playgroud)