首页 > 解决方案 > 为不同类中的方法提供“this”上下文的最佳实践

问题描述

我有 2 个类,其中一个是整个应用程序使用的通用实用程序类。我想this在被调用者实用程序类中引用调用者类的属性。

我不确定最好的做法是什么。

我已经提供了一个我正在尝试做的例子。

我可以使用一种情况.call来提供正确的上下文,或者我可以作为函数参数this传入。this

class Caller {

  doSomething() {
    Utility.calledMethod.call(this, 'paramStr');
    Utility.calledMethodWithThis(this, 'paramStr');
  }

  doAnotherThing(param) {
    console.log(param);
  }
}

// Shared Class of utility methods used for entire application
class Utility {

  static calledMethod(param) {
    this.doAnotherThing(param);
  }

  static calledMethodWithThis(self, param) {
    self.doAnotherThing(param);
  }
}

const caller = new Caller();
caller.doSomething();

https://jsfiddle.net/pvafedho/

标签: javascript

解决方案


这看起来像是您可以使用 mixin 的场景。

按照此页面中的示例:https ://javascript.info/mixins

您的代码可能如下所示:

// Shared Class of utility methods used for entire application
let utilityMixin = {
  calledMethod(param) {
        this.doAnotherThing(param);
  }
}

class Caller {
  constructor() {
    this.mystring = 'hello!'  
  }

  doSomething() {
    this.calledMethod(this.mystring);
  }

  doAnotherThing(param) {
    console.log(param);
  }
}

Object.assign(Caller.prototype, utilityMixin );

const caller = new Caller();

caller.doSomething();

推荐阅读