function testLet(){
var x=9;
return{
y:x,
getX: function(){
return ++x;
},
}
}
var obj = new testLet();
console.log(obj.y); //9 as expected
console.log(obj.getX()); //10 as expected
console.log(obj.getX()); //11 as expected
console.log(obj.y); //I expect it 11.. but it stays 9
Why the last line returns 9 instead of 11 as x is in the same scope?
y:x
means "Copy the current value of x
to the property y
".
The value, at the time, is 9
.
Subsequent changes to the value of x
won't change the value of y
.
You can either change your getX
function to modify this.y
, or you can change the y
property to be a getter function which reads the current value of x
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.