为什么类实例方法在调用后导致未定义。超时功能正确吗?

时间:2019-09-20 14:44:36

标签: javascript javascript-objects

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")

2 个答案:

答案 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