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)




Menu