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

时间:2018-04-08 09:55:20

标签: javascript javascript-objects

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,
}

1 个答案:

答案 0 :(得分:1)

当您引用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);