gpt4 book ai didi

javascript - javascript super 调用中变异了 'this',如何处理?

转载 作者:行者123 更新时间:2023-12-03 07:37:44 24 4
gpt4 key购买 nike

抱歉,如果这很难解释。假设类 Y 扩展类 Z,类 X 扩展类 Y

问题是,如果一个类没有方法,它会调用它的父类(super class),到目前为止一切都很好。

X.prototype.v = function{return this.getV();}//getV()在类X中不存在

由于类 X 扩展了类 Y 并且 getV() 存在于类 Y 中,因此调用如下:

Y.prototype.getV = function{return this.parent().getV()+1} 

工作函数parent()返回其父类(super class)的一个实例。假设 z 还有一个方法 getV,它返回一个实数 int 值。

Z.prototype.getV = function{return 1}

所以Y类中的函数getV()的意思是返回Z中的getV值加1,并将其发送给最低类X。

大部分接线部分都在这里。只要从 X.v() 调用 getV 方法,y.getV() 中的 'this' 就引用 X,而不是 Y!

因此 Y 中的函数 getV() 变为 X.parent().getV()+1,并且我得到“超出最大调用堆栈大小”

解决这个问题的一个愚蠢但极其有效的方法是编写

this.parent().parent().getV()+1

双亲使发送者 Z 不是 y,那么调用 X.getV() 时返回 2

这很愚蠢,因为如果调用者是 Y 本身,比如 Y.getV(),我认为“this”在这里正确地表示 Y,那么有太多的parent()调用,导致它未定义。

一些想法,比如我们可以摆脱“这个”,并使用另一种方式来获取当前类。不太理想的方法可能是跟踪所有类的所有函数,并设置正确的parent()数量。我相信还有更多。然而,它们都还没有经过测试。

取自上面代码片段的最小代码示例可以是:

class Z{

}
class Y extends Z{

}
class X extends Y{

}

X.prototype.v = function{
return this.getV();
}

Y.prototype.getV = function{
return this.parent().getV()+1;
}

Z.prototype.getV = function{
return 1;
}

var x = new X();
console.log(x.v());

最佳答案

如果你使用ES6类语法,你应该使用super:

class Z {
getV() {
return 1;
}
}
class Y extends Z {
getV() {
return super.getV() + 1;
}
}
class X extends Y {
v() {
return super.getV(); // or this.getV();
}
}
new Z().getV(); // 1
new Y().getV(); // 2
new X().getV(); // 2
new X().v(); // 2

在 ES5 中,我会使用类似的东西

function extend(f1, f2) {
f1.prototype = Object.create(f2.prototype);
f1.prototype.constructor = f1;
f1.super = f2.prototype;
}
function Z(){}
Z.prototype.getV = function() {
return 1;
};
function Y(){}
extend(Y, Z);
Y.prototype.getV = function() {
return Y.super.getV.call(this) + 1;
};
function X(){}
extend(X, Y);
X.prototype.v = Y.prototype.getV;
new Z().getV(); // 1
new Y().getV(); // 2
new X().getV(); // 2
new X().v(); // 2

关于javascript - javascript super 调用中变异了 'this',如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35542717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com