The thing is that the .apply()
fires the function, and you don't want to fire the function, you want to create a function with changed this
context.(关键是.apply()
会触发该函数,而您不想触发该函数,而是想创建一个更改了this
上下文的函数。)
To do so, you want to use a .bind()
method which creates a function but does not fire it.(为此,您想使用.bind()
方法创建一个函数,但不触发它。) Look at this code:(看这段代码:)
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);
So the method1
in the Second
class is a copy of the method with the same name from class First
.(因此, Second
类中的method1
是该方法的副本,其名称与First
类相同。) It's created using bind()
and changed this
to the Second
class context.(它使用创建bind()
改变this
为Second
类环境。)
However, the theList
field in the Second
class is a result of invoking the method2()
from the First
class with changed this
context.(但是, Second
类中的theList
字段是在更改this
上下文的情况下从First
类调用 method2()
的结果。) It is not a function, it's a result of the function.(它不是函数,而是函数的结果。)
See the difference?(看到不同?) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…