How js implements the recoverability of changes to the properties of variables, as shown in the following figure.

clipboard.png

after changing the attribute of a variable myRecord , calling the rollback method of the variable myRecord will give up the change to the attribute of the variable myRecord . How can this method be implemented?

Mar.10,2021

just put a field in the variable to store the last result (remember not to keep the reference relationship between the two)
overwrite the current object with the last result when calling rollback .
compares the results twice when calling save , and then performs the operations of POST and PUT .


you mean that after changing the properties of myRecord , call the rollback method of myRecord , and reset the variable value of myRecord after calling the method?


the following is a simple implementation done through Object.defineProperty for your reference:

var obj = {
    rollback:function(){
        if(this['old_value'])
            this.value = this['old_value'];
    },
    save:function(){
        delete this['old_value'];
    }
}

Object.defineProperty(obj, "name",{
    set:function(newVal){
        this['old_value'] = this.value;
        this.value =  newVal;
    },
    get:function(){
        return this.value;
    }
})



obj.name="abc";
console.log(obj.name) //abc
obj.name="123";
console.log(obj.name) //123
obj.rollback()
console.log(obj.name) //abc
obj.name="def";
console.log(obj.name) //def
obj.save()
console.log(obj.name) //def


will output

abc
123
abc
def
def
Menu