gpt4 book ai didi

javascript - 有没有更简洁的方法来引用对象的局部变量?

转载 作者:行者123 更新时间:2023-11-30 20:37:00 24 4
gpt4 key购买 nike

CLOCK 对象中,我有 initCount() 方法,它将值设置为属性 timeTotaltimeZerotimeStep

我正在寻找一种无需声明局部变量即可将新值传递给 timeStep 的方法。这是代码片段,下面是代码的更大上下文:

initCount: function() {
CLOCK.timeTotal = 5;
let localTimeTotal = 5;
CLOCK.timeZero = 0;
let localTimeZero = 0;
CLOCK.timeStep = localTimeZero / localTimeTotal;
}

const CLOCK = {
initCount: function() {
CLOCK.timeTotal = 5;
let localTimeTotal = 5;
CLOCK.timeZero = 0;
let localTimeZero = 0;
CLOCK.timeStep = localTimeZero / localTimeTotal;
},
timerReset: function() {
context.clearRect(0, 0, canvas.width, canvas.height);
//INITIALIZING FUNCTIONS AND BUTTONS
CLOCK.initCount();
},
timerSwitch: false,
sessionSwitch: true,
timeTotal: undefined,
timeZero: 0,
timeStep: undefined,
timerInterval: undefined,
}

最佳答案

当您引用 CLOCK 对象并使用 CLOCK 命名空间执行您的函数时,请在您的函数中使用“this”,即 CLOCK.initCount()

你可能想为一些面向对象的糖使用类结构

您的方法 - 纯 JS 对象

const CLOCK = {
initCount: function() {
this.timeTotal = 5;
this.timeZero = 0;
this.timeStep = this.timeZero / this.timeTotal;
},
timerReset: function() {
context.clearRect(0, 0, canvas.width, canvas.height);
//INITIALIZING FUNCTIONS AND BUTTONS
this.initCount();
},
timerSwitch: false,
sessionSwitch: true,
timeTotal: undefined,
timeZero: 0,
timeStep: undefined,
timerInterval: undefined,
}

CLOCK.initCount();
console.log(CLOCK);

关于javascript - 有没有更简洁的方法来引用对象的局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49716630/

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