简体   繁体   English

Javascript OO,问题通过继承

[英]Javascript OO, issue going trough inheritance

I've got an issue to fix with some kind of inheritance in JS. 我有一个问题可以解决JS中的某种继承问题。

I've set a small jsfiddle to explain, looking at: 我设置了一个小jsfiddle来解释,看:

V1 http://jsfiddle.net/FFTj4/5/ V1 http://jsfiddle.net/FFTj4/5/

function Vehicule(name) ...

Here the result are not as expected but easily explained. 这里的结果不是预期的,而是容易解释的。 I'm calling parent constructor with apply which scope the function to the "calling" object where the name is set. 我正在调用父构造函数,并应用该函数的作用域到设置名称的“调用”对象。 So far car and sportcar name are not set in their vehicule prototype so when i ask for the name and going up to vehicule name is undefined. 到目前为止,汽车和运动车的名称尚未在其车辆原型中设置,因此当我要求输入名称并且上车时仍未定义。

I fixed it with that: 我用它修复了它:

V2 (uncomment v2 section in the jsfiddle) Well now i'm also "scoping" the getName call to ensure i got my "name". V2(jsfiddle中的uncomment v2部分)现在,我也在“作用域” getName调用,以确保获得我的“名称”。 I though it was fixed! 我虽然是固定的! So i applied the fix to SportCar also 所以我也将修复程序应用于SportCar

V3 (uncomment v3 section in the jsfiddle) Well it could not be that easy, now i'm locked SportCar call Car getName, but car is scoped to SportCar so when car "tried" to call Vehicule getName it call SPortCar getName instead, and so on, Maximum call stack size exceeded. V3(在jsfiddle中取消注释v3部分)嗯,这并不容易,现在我锁定了SportCar调用Car getName,但是car的作用域是SportCar,因此当汽车“尝试”调用Vehicule getName时,它将调用SPortCar getName,并且依此类推,超出了最大调用堆栈大小。

I need to come up with a way to be able to tu call the current object superClass, no matter if called with an apply, and of course keep the scope of the topmost object :/ 我需要想出一种方法来能够调用当前对象的superClass,无论是否使用apply调用,当然都应保留最顶层对象的范围:/

I've run out of ideas, been on this for almost 2 weeks now. 我已经没有足够的想法了,现在已经花了将近2周的时间。

Thank you ! 谢谢 !

In line: 排队:

Car.prototype.superClass = Vehicule;

You are assinning function, not an instance, so you can't call 您是函数,不是实例,因此您无法调用

this.superClass.prototype.getName();

becouse you have no context. 因为你没有上下文。 No object was created. 没有创建对象。 You need to do this this way: 您需要这样做:

this.superClass.prototype.getName.call(this);

Then it should work like you want :) 然后它应该像您想要的那样工作:)

But, in your code it will not work becouse you are overwriting superClass . 但是,在您的代码中它将无法工作,因为您将覆盖superClass You need to use "class" name for this: 您需要为此使用“类”名称:

Car.prototype.getName.call(this);

Or just don't assign superClass to prototype ;) 或者只是不将superClass分配给原型;)

Here is a simple explanation of prototypal inheritance. 是原型继承的简单说明。 Comments are in polish, but JS is JS ;) 注释用波兰语表示,但JS是JS;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM