I have defined an object and defining a property using javascript's defineProperty method.
我已经定义了一个对象并使用javascript的defineProperty方法定义了一个属性。
var obj ={};
Object.defineProperty(obj,'b',{get:function(){
return 5},
set:function(value){
this.b = value}
});
but when i am setting the value of b using below statement
但是当我使用下面的语句设置b的值时
obj.b = 25
it giving me
它给了我
RangeError: Maximum call stack size exceeded
RangeError:超出最大调用堆栈大小
How can i set the value of b?
我该如何设置b的值?
1 个解决方案
#1
2
You are using setter in infinite recursive loop, code inside setter is using it again:
你在无限递归循环中使用setter,setter中的代码再次使用它:
this.b = value; //this use setter of b again
change it to any different variable name like:
将其更改为任何不同的变量名称,如:
this.bVal=value;
All code:
//example object
obj={};
Object.defineProperty(obj,'b',{
get:function(){
return this.bVal;
},
set:function(value){
this.bVal=value;
}
});
obj.b="Test text value of property b";
console.log(obj.b);
Why previous code was infinite loop? Take a look:
为什么以前的代码是无限循环?看一看:
obj.b=12; //this code run set function
Inside set
function was:
内部设定功能是:
this.b=value; //this code also runs set function because this===obj
So set
function is called again and again and never stops.
因此一次又一次地调用set函数并且永远不会停止。
#1
2
You are using setter in infinite recursive loop, code inside setter is using it again:
你在无限递归循环中使用setter,setter中的代码再次使用它:
this.b = value; //this use setter of b again
change it to any different variable name like:
将其更改为任何不同的变量名称,如:
this.bVal=value;
All code:
//example object
obj={};
Object.defineProperty(obj,'b',{
get:function(){
return this.bVal;
},
set:function(value){
this.bVal=value;
}
});
obj.b="Test text value of property b";
console.log(obj.b);
Why previous code was infinite loop? Take a look:
为什么以前的代码是无限循环?看一看:
obj.b=12; //this code run set function
Inside set
function was:
内部设定功能是:
this.b=value; //this code also runs set function because this===obj
So set
function is called again and again and never stops.
因此一次又一次地调用set函数并且永远不会停止。