Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

javascript - 如何重新定义“ this”并重用另一个类的方法。 多态性(how redefine 'this' and reuse another class's method. Polymorphism)

I would love to make polymorphisme in js with classes reassigning this .(我很想在js中使用重新分配此类的类来实现多态。)

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:(另一个已经从另一个Parent类中骚扰的类:) 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 :(当我运行Second时,它会引发错误: apply无法应用于method1,因为它没有防御,但是当我创建实例时,它将失去Second的以下范围:) 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(我还需要为First.method1提供参数) i tried this answer but that wasnt working(我尝试了这个答案,但那没有用)   ask by AlexNikonov translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()改变thisSecond类环境。) 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?(看到不同?)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...