gpt4 book ai didi

javascript - 引用错误,Magic 未定义。但它是在测试参数中定义的吗?

转载 作者:行者123 更新时间:2023-12-02 23:18:20 25 4
gpt4 key购买 nike

我正在研究这个型:https://www.codewars.com/kata/magic-the-gathering-number-3-spell-stack/train/javascript .

它在运行示例测试时抛出此错误:

ReferenceError: Magic is not defined
at /home/codewarrior/index.js:7:1
at Object.handleError
<anonymous>

我研究了原型(prototype)的工作原理,我的代码似乎是正确的。

这是我到目前为止的代码:

// Create the Magic object with a spellStack method
// Happy Casting!
Magic.prototype.spellStack = (card) => {
console.log(card);
}

测试参数如下:

  Test.describe("It should add and remove spells on the stack", function() {
let spells = [{'name':'Lightning Bolt', 'type': 'instant'}, {'name': 'Giant Growth', 'type': 'instant'},
{'name':'Time Walk', 'type': 'sorcery'}, {'name': 'Ponder', 'type': 'sorcery'}];
var myMagic = new Magic();

Test.assertSimilar(myMagic.spellStack(spells[2]), 1);
Test.assertSimilar(myMagic.spellStack(spells[0]), 2);
Test.assertSimilar(myMagic.spellStack(spells[0]), 3);
Test.assertSimilar(myMagic.spellStack(spells[1]), 4);
Test.assertSimilar(myMagic.spellStack(), spells[1]);
Test.assertSimilar(myMagic.spellStack(), spells[0]);
Test.assertSimilar(myMagic.spellStack(), spells[0]);

Test.it("Should throw an error if trying to add a sorcery to a stack with spells:", function() {
Test.expectError(()=>myMagic.spellStack(spells[3]));
Test.expectError(()=>myMagic.spellStack(spells[2]));
});

Test.it("Should throw an error if trying to retrieve a spell when the stack is empty:", function() {
Test.assertSimilar(myMagic.spellStack(), spells[2], "Removing the last spell from the stack");
Test.expectError(()=>myMagic.spellStack());
});
});

至少它应该给出一个错误,但也应该控制台输出函数输入。

最佳答案

在这条线上

Magic.prototype.spellStack = (card) => {

您正在原型(prototype)上设置属性,但是 Magic 是在哪里定义的? Magic 尚不存在。

您需要先定义它

function Magic() {}
Magic.prototype.spellStack = (card) => {
console.log(card);
}

关于javascript - 引用错误,Magic 未定义。但它是在测试参数中定义的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57066335/

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