js is out of scope when setting setter

Sometimes, when we set the attributes of an object, we need to make some changes to the assigned value, for example, set the a attribute of an object to 2, but in fact we need it to return 2*3 when outputting. At this time, we may need to use the setter to set it, but if it is written like this,

let myObj = {
    
    
	get a () {
    
    
		return this.a
	},
	set a (val) {
    
    
		this.a = val * 3
	}
}
myObj.a = 2 // 报错

Will report the following error

Uncaught RangeError: Maximum call stack size exceeded

Why is this?
Because we have assigned a value to the a property in the set, the set we set for the myObj object will be called again in the set, resulting in constant loop calls.
If you want to operate the assignment in the set, we can solve this problem like this. A built-in _a in the myObj object is as follows:

let myObj = {
    
    
	get a () {
    
    
		return this._a
	}
	set a (val) {
    
    
		this._a = val * 3
	}
}
myObj.a = 2 // 6

Guess you like

Origin blog.csdn.net/m0_38038767/article/details/110792034