gpt4 book ai didi

javascript - 如何在类中设置局部变量

转载 作者:太空宇宙 更新时间:2023-11-03 22:56:39 25 4
gpt4 key购买 nike

class Calculator {
constructor() {
console.log(`Enter the numbers and the operation index you want to perform:
1) Addition
2) Substraction
3) Multiplication
4) Division`);

this.calculate();
}

/**
* @param {number} firstValue get the first value
* @param {number} secondValue get the second value
*/
addition(firstValue, secondValue) {
return firstValue + secondValue;
}

/**
* @param {number} firstValue get the first value
* @param {number} secondValue get the second value
*/
subtraction(firstValue, secondValue) {
return firstValue - secondValue;
}

/**
* @param {number} firstValue get the first value
* @param {number} secondValue get the second value
*/
multiplication(firstValue, secondValue) {
return firstValue * secondValue;
}

/**
* @param {number} firstValue get the first value
* @param {number} secondValue get the second value
*/
division(firstValue, secondValue) {
if (secondValue != 0) {
return firstValue / secondValue;
}
return 'Cannot perform division by 0';
}

calculate() {
prompt.get(propertiesPrompt, (error, values) => {
if (error) {
throw new Error(error);
}

console.log(operationResult[values.operation](values.valueOne, values.valueTwo));
prompt.get(choiceResponse, (responseError, response) => {
if (responseError) {
throw new Error(responseError);
}

if (response.optionSelected.toLowerCase() == 'y') {
this.calculate()
}
});
});
}
}

在上面的代码中,我想删除加减乘除方法中的参数,并想在类中设置一个变量属性,以便我可以直接调用方法中存储的值并进行操作。怎么可能做到这一点?

最佳答案

局部类变量的正确名称是字段:

class Calculator {
constructor() {
this.field = 10
}

show() {
console.log(this.field)
}
}

类的函数名称也是一个方法

方法和字段一起是成员

关于javascript - 如何在类中设置局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60501974/

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