【问题标题】:javascript mixin access to objects thisjavascript mixin 访问对象 this
【发布时间】:2018-02-15 11:57:06
【问题描述】:

我已经创建了一个对象和一个 mixin,我已经将 mixin 分配给了 Object,但是我似乎无法从 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();

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

【问题讨论】:

    标签: javascript node.js mixins


    【解决方案1】:

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

    一个箭头函数表达式...并且没有自己的 this、arguments、super 或 new.target。

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

    【讨论】:

    • 只是为了表明你不能在不了解它们的情况下就跳上闪亮的新功能。
    猜你喜欢
    • 2016-02-26
    • 1970-01-01
    • 2013-03-08
    • 1970-01-01
    • 2015-12-18
    • 2016-01-31
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    相关资源
    最近更新 更多