javascript mixin 访问对象 this

标签 javascript node.js mixins

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

mixin.js

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

对象.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();

我收到错误无法读取未定义的属性“标题”

最佳答案

您需要放弃箭头函数,转而使用普通函数,因为箭头函数失去了 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

关于javascript mixin 访问对象 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48806723/

相关文章:

javascript - 如何测试Javascript中另一个函数的函数调用次数?

javascript - 在收到特定操作时将商店重置为初始状态

javascript - jqgrid 在下拉选择上加载网格

node.js - 无法加载 c++ bson 扩展,使用纯 JS 版本——没有 Mongoose ,没有 express ,只有 Node 驱动程序

node.js - 使用winston-mongodb后收到警告[当前服务器发现和监控引擎已被弃用]

Ruby:在类方法中使用模块方法

Javascript减少函数错误

javascript - module.js 474 抛出错误

css - 如何用前后 block 干掉sass mixin代码?

css - 使用 sass @mixin 和 @content 时出现多个媒体查询问题