【问题标题】:how redefine 'this' and reuse another class's method. Polymorphism如何重新定义“this”并重用另一个类的方法。多态性
【发布时间】:2019-11-28 20:03:59
【问题描述】:

我很想在 js 中使用重新分配 this 的类来实现多态性。

我有一个类简化为:

class First{
  method1 = function(aVar) { this.list.map (e => e === aVar)}
}

和另一个已经从另一个父类继承的类:

class Second extends Parent{
  constructor(){
    this.list = ['some elements'];
    this.method1 = First.method1.apply(this, arguments)
}

Parent 不能从 First 扩展; 当我运行 Second 时,它会抛出一个错误:apply 不能应用于 method1 因为它是 undefiend, 但是当我创建一个实例时,它会丢失 Second's this 范围:

class Second extends Parent{
  constructor(){
    this.list = ['some elements'];
    this.method1 = (new First).method1.apply(this, arguments)
}

我还需要为 First.method1 提供参数

我试过这个answer,但没用

【问题讨论】:

  • 不要使用类字段来定义方法,而是使用普通的方法定义。
  • 你到底想在你的Second 课堂上用method1 做什么?请同时显示预期用途。目前还不清楚那些arguments 在那里做什么(Firstmethod1 甚至不接受任何东西),以及你期望this.list 解决什么问题。

标签: javascript ecmascript-6 es6-class


【解决方案1】:

问题是.apply() 触发了该函数,而您不想触发该函数,您想创建一个更改了this 上下文的函数。为此,您需要使用 .bind() 方法来创建一个函数但不触发它。看这段代码:

class First {
 
  method1() {
    this.list.map(e => e)
    console.log('I got called');
  }
  
  method2() {
    return this.list;
  }
}

class Parent {}

class Second extends Parent {
  constructor(){
    super();
    
    this.list = ['second class list'];
    this.method1 = (new First()).method1.bind(this)
    
    this.theList = (new First()).method2.apply(this);
  }
}

const sec = new Second();
sec.method1();
console.log(sec.theList);

所以Second 类中的method1 是类First 中同名方法的副本。它是使用bind() 创建的,并将this 更改为Second 类上下文。

但是,Second 类中的theList 字段是调用来自First 类的method2() 更改this 上下文的结果。不是函数,是函数的结果。

看到区别了吗?

【讨论】:

    猜你喜欢
    • 2022-11-01
    • 1970-01-01
    • 2021-10-03
    • 1970-01-01
    • 2014-02-19
    • 2016-06-22
    • 1970-01-01
    • 2012-05-03
    • 2011-03-07
    相关资源
    最近更新 更多