繁体   English   中英

全局变量在 class 实例 JavaScript 内部使用

[英]Global variables use inside the class instance JavaScript

我在一个 js 文件中声明并导出了 class。 在这个文件中,我的 class 实例可以使用全局变量。 我将此 class 导入到测试文件中,我遇到了一个未定义变量的问题。

这是我的 class

export class GuessingGame {
    setRange(min, max) {
        this.min = min
        this.max = max
    }
    guess() {
        if(this.min + 1 === number) {
            return this.min + 1
        } else if(this.max - 1 === number) {
            return this.max - 1
        } else {
        return Math.round((this.max - this.min) / 2 + this.min)
        }
    }
    lower() {
        if(this.guess() > number) {
            this.max = this.guess()
        }
    }
    greater() {
        if(this.guess() < number) {
            this.min = this.guess()
        }
    }
}

如果我用这个 class 在文件中声明 var number - class 实例可以使用它而不会出现任何错误。 但!

这是测试文件,它应该使用全局变量 const number。 但它给了我错误 ReferenceError: number is not defined

import { GuessingGame } from './rolling-scopes-guessing-game.js';
import chai from 'chai';
import sinonChai from'sinon-chai';

global.expect = chai.expect;
chai.use(sinonChai);

describe('GuessingGame', () => {
describe('#guess', () => {
it('should guess number 409 with max value 4048', () => {
    const number = 409;
    const game = new GuessingGame();
    game.setRange(0, 4048)

    let result = game.guess();
    game.lower();
    result = game.guess();
    game.lower();
    result = game.guess();
    game.lower();
    result = game.guess();
    game.greater();
    result = game.guess();
    game.greater();
    result = game.guess();
    game.lower();
    result = game.guess();
    game.lower();
    result = game.guess();
    game.greater();
    result = game.guess();
    game.greater();
    result = game.guess();
    game.greater();
    result = game.guess();
    game.lower();
    result = game.guess();

    expect(result).to.equal(number);
    });
});
});

您的全球number听起来很像static字段:

 class GuessingGame { static number = 1234; setRange(min, max) { this.min = min this.max = max } guess() { if(this.min + 1 === number) { return this.min + 1 } else if(this.max - 1 === number) { return this.max - 1 } else { return Math.round((this.max - this.min) / 2 + this.min) } } lower() { if(this.guess() > number) { this.max = this.guess() } } greater() { if(this.guess() < number) { this.min = this.guess() } } } console.log(GuessingGame.number);

您可以在任何需要的地方设置GuessingGame 如果你想让它保持不变,你可以将它定义为

    static get number() {
        return 1234;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM