DefineProperty accessor property error stack overflow

var book = {
    year:2004,
    edition:1
}
Object.defineProperty(book,"year",{
    get:function(){
        return this.year
    },
    set:function(newVal){
        if(newVal>2004){
            this.year = newVal ;
            this.edition += newVal - 2004 ;
        }
    }
});
book.year = 2005 ;
console.log(book.edition)

as shown above, running directly will report an error Maximum call stack size exceeded

at Object.set [as year]

but if you add an identifier or other letter before the year, there will be no problem. Who can answer it?

Mar.05,2021

you define setter, to year and then assign a value to year in setter, which calls the setter, loop and calls


in this case, it is generally recommended to use closures to handle circular calls


[Getter/Setter]

var book = {
    year:2004,
    edition:1
}

let temp=book.year //book = {    year:2004,    edition:1}

Object.defineProperty(book,"year",{
    get:function(){
        return temp
    },
    set:function(newVal){
        if(newVal>2004){
            temp = newVal ;
            this.edition += newVal - 2004 ;
        }
    }
});             //book = {    year:[Getter/Setter],    edition:1}
book.year = 2005 ;
console.log(book.edition)




MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b36abe-2c036.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b36abe-2c036.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?