aeri.attack / aeri.magicAttack会导致Attack()函数。但是,如果我尝试调用该函数,则会导致未定义。为什么。
我尝试做一个Character实例,看它是否只是子类,但不是。
如果有人可以告诉我即时通讯是否正确执行setTimeout函数,那我将永远爱你。
PS PS我无法测试超时方法是否正常工作,因为我的方法都没有正常工作。
class Character {
constructor(name, weapon) {
this.name = name;
this.weapon = weapon;
}
attack(){
this.name + ' attacks with ' + this.weapon;
}
}
class Elf extends Character {
constructor(name, weapon, type) {
super(name, weapon);
this.type = type;
}
magicAttack() {
this.name + ' chants ';
setTimeout(function(){this.type; }, 3000);
}
}
const aeri = new Elf("Aeri", "bow", "air")
const bob = new Character("Bob", "yawn")
答案 0 :(得分:1)
只需在您的代码中添加console.log即可:
deleted
答案 1 :(得分:1)
原始帖子中的代码不符合OP期望的原因有很多。
class Character {
constructor(name, weapon) {
this.name = name;
this.weapon = weapon;
}
attack(){
this.name + ' attacks with ' + this.weapon; // (1)
}
}
class Elf extends Character {
constructor(name, weapon, type) {
super(name, weapon);
this.type = type;
}
magicAttack() {
this.name + ' chants '; // (2)
setTimeout(function(){this.type; }, 3000); // (3)
}
}
const aeri = new Elf("Aeri", "bow", "air")
const bob = new Character("Bob", "yawn")
(1)attack()
方法缺少return
语句
(2)this.name + ' chants ';
语句不执行任何操作,因为串联的结果未分配给变量或传递给方法,因此将其丢弃。
(3)传递给setTimeout
的匿名函数引用了this.type
,但在给定how this
works in JavaScript的情况下,type
在此上下文中未定义(因为this
是实际上是匿名函数本身。)
要查看调用该方法的结果,需要对原始代码示例进行以下更改:
class Character {
constructor(name, weapon) {
this.name = name;
this.weapon = weapon;
}
attack(){
return this.name + ' attacks with ' + this.weapon; // (1)
}
}
class Elf extends Character {
constructor(name, weapon, type) {
super(name, weapon);
this.type = type;
}
magicAttack() {
const chant = this.name + ' chants '; // (2)
setTimeout(function(){ console.log(chant); }, 3000); // (3)
}
}
const aeri = new Elf("Aeri", "bow", "air")
const bob = new Character("Bob", "yawn")
aeri.magickAttack();
希望这会有所帮助!
Jan