javascript mixin 访问对象 this

javascript mixin access to objects this

我已经创建了一个对象和一个 mixin,我已经将 mixin 分配给对象,但是我似乎无法从 mixin 访问该对象,对吗?

mixin.js

module.exports = {
  doSomething: () => {
    let something = this.something.title;
  }
};

object.js

class Thing {   
  constructor(something) {
    this.something = something;   
  }

  _otherFunction() {
    // does stuff
  } 
}

module.exports = Thing;

index.js

const Something = require('./mixin');
const Thing = require('./Object');

Object.assign(Thing.prototype, Something);

然后当我实例化 Thing 并调用 doSomething() 时,它就无法访问 this.something... 所以

let thing = new Thing({title: 'abc'});
thing.doSomething();

我收到错误 Cannot read 属性 'title' of undefined

您需要放弃箭头函数,转而使用普通函数,因为箭头函数失去了 this 的作用域。

class Thing {   
  constructor(something) {
    this.something = something;   
  }
}

const mixin = {
  // changed arrow function to regular function
  doSomething: function () {
    console.log(this.something.title)
  }
}

const thing = new Thing({title: 'abc'})
Object.assign(thing, mixin)
thing.doSomething()

来自MDN: Arrow Functions

An arrow function expression... and does not have its own this, arguments, super, or new.target.

很多人错误地认为箭头函数的唯一特点是语法更短——事实并非如此。它的主要实用功能是它不会创建自己的 this.