Reputation: 5598
I would love to make polymorphisme in js with classes reassigning this.
I have one class simplified to this:
class First{
method1 = function(aVar) { this.list.map (e => e === aVar)}
}
and another class which is already has inharitance from another Parent class:
class Second extends Parent{
constructor(){
this.list = ['some elements'];
this.method1 = First.method1.apply(this, arguments)
}
The Parent cannot be extended from the First; When i run Second it throws an error: apply cannot be applied to method1 because it's undefiend, But when i create an instance it losts Second's this scope :
class Second extends Parent{
constructor(){
this.list = ['some elements'];
this.method1 = (new First).method1.apply(this, arguments)
}
Also i need to provide arguments to First.method1
i tried this answer but that wasnt working
Upvotes: 0
Views: 378
Reputation: 8515
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. To do so, you want to use a .bind()
method which creates a function but does not fire it. 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
. It's created using bind()
and changed this
to the Second
class context.
However, the theList
field in the Second
class is a result of invoking the method2()
from the First
class with changed this
context. It is not a function, it's a result of the function.
See the difference?
Upvotes: 1