我有两个类,B类扩展了A类。在B类中,我正在做一些canvas操作,因此需要调用图像加载的回调。在回调中,我想调用父类的方法。但是,如果我将这行代码放入回调中,我会收到一个语法错误“Uncaught SyntaxError:'super'关键字在这里意外”。知道如何在回调中使上下文可用,以便我可以调用父类的方法吗?
干杯汤姆
class A{
super(){
}
myMethod(){
console.log("mymethod of A");
}
}
class B extends A{
constructor(){
super();
}
myMethod(){
var canvas = window.document.getElementById("myCanvas");
var context = canvas.getContext('2d');
context.canvas.width = 200;
context.canvas.height = 100;
context.fillStyle = "#ffff00";
context.font = "15px Arial";
context.fillText("Hello World!", 0, context.canvas.height);
var image = document.createElement("img");
image.src = canvas.toDataURL("image/png");
this.img = image;
image.onload = async function(){
super.myMethod();// having thise line in the code results in "Uncaught SyntaxError: 'super' keyword unexpected here"
console.log("callback");
}
}
}
答案 0 :(得分:3)
您需要在此处使用arrow function,这会保留定义它的方法的this
和super
:
myMethod(){
…
image.onload = () => {
super.myMethod();
};
}
请注意,没有理由创建事件处理程序async
。