javascript - ES 6 类 : Access "this" in another scope

标签 javascript ecmascript-6

我在 NodeJS 4 中有一个 ES6 类。 在构造函数中,我想修改一个对象的原型(prototype),以便它现在使用这个类实例来执行操作。

但是,当然,在原型(prototype)范围内,this不引用我正在创建的类的实例。

class Generic {
  constructor() {
    this.myClass = util._extend({}, aClass); //shallow copy
    this.myClass.prototype.run = function(fn) {
      var str = this.toString;
      //in the next line, _this_ should refer to the Generic instance.
      this.run(str, fn);
    };
  }

  do() {
    return this.myClass;
  }

  run(str, fn) {
    ...
  }

如何引用在 myClass 原型(prototype)范围上创建的通用类实例?

最佳答案

一些选项:

  • 绑定(bind):

    this.myClass.prototype.run = (function(fn) {
      // `this` is the Generic instance.
    }).bind(this);
    
  • 那个:

    var that = this;
    this.myClass.prototype.run = function(fn) {
      // `that` is the Generic instance.
    };
    
  • 箭头函数:

    this.myClass.prototype.run = fn => {
      // `this` is the Generic instance.
    };
    

关于javascript - ES 6 类 : Access "this" in another scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33334488/

相关文章:

javascript - 使用 javascript 关闭纸张对话框或纸张操作对话框

javascript - ES6 解构语法可能出现的奇怪行为

javascript - 将 JavaScript 对象映射到哈希数组

javascript - 箭头函数 vs 胖箭头函数

javascript - 在js函数中使用通配符

javascript - D3 简单条形图不更新

javascript - 创建[下载]按钮的指令

javascript - 在文件中设置 Harmony 标志

javascript - 如何使用 es6 样式导入导入 MongoDB?

javascript - Brain.js - 无法从 json 文件加载网络