我在react-native中使用javascript es-06语法来开发移动应用程序。这是我的代码:
超级课程:
export class ApiCallback {
onResponse = (responseJson) => {
console.log("super response")
}
onError = (error) => {
console.log("super error")
}
}
基类:
export class LoginCallback extends ApiCallback {
onResponse(responseJson) {
super.onResponse(responseJson)
console.log(responseJson)
}
onError(error) {
super.onError()
console.error(error)
}
}
用法:
export class AuthenticationInteractor {
doLogIn(loginCallback: LoginCallback) {
fetch("http://google.com",
{
method: "GET"
})
.then((responseJson) => {
loginCallback.onResponse(responseJson)
})
.catch((error) => {
loginCallback.onError(error)
})
}
}
和
new AuthenticationInteractor().doLogIn(new LoginCallback())
这里,它不是调用基类方法(在onResponse()中打印所有共振json),而是调用父类的onResponse()函数并打印
“超级回应”
是基类的onResponse()函数的结果。
答案 0 :(得分:1)
简单的答案是:你不应该使用箭头函数作为类中的方法。
export class ApiCallback {
onResponse(responseJson) {
console.log("super response")
}
onError(error) {
console.log("super error")
}
}
复杂的答案是:当您将类方法声明为箭头函数时,它不会被添加到类原型中,但会在初始化时添加到对象中。在您的情况下,您将LoginCallback方法添加到原型,但在初始化时,它们被父类的方法覆盖。
因此,最好始终将经典函数用作类方法。但是不要忘记将上下文绑定到它们。
答案 1 :(得分:-1)
请参阅下面的代码片段,它将提高对功能定义的理解。
我认为abc = function(){}
的优先级大于function abc(){}
。
因此,要替换派生类中的函数,必须以相同的方式定义函数。
所以在你的情况下使用
父类上的onResponse(responseJson){console.log(“superresponse”)}
将解决问题。
abc = function(){
console.log("abc");
}
function abc(){
console.log("def");
}
abc();
function def(){
console.log("abc");
}
function def(){
console.log("def");
}
def();
var ghi =function(){
console.log("abc");
}
var ghi = function(){
console.log("def");
}
ghi();