Javascript's equivalent of destruct in object model

后端 未结 3 1246
走了就别回头了
走了就别回头了 2020-12-17 07:21

Since I\'ve dealt in the past with javascript\'s funky \"object model\", I assume there is no such thing as a destructor. My searches were mildly unsuccessful, so you guys a

3条回答
  •  余生分开走
    2020-12-17 08:04

    In other languages the destructor is handy for implementing the memento pattern. That's actually what lead me to this topic. For example, in a click event it'd be nice to have a generic function that I can pass the event target to that disables the target and then re-enables it when it falls out of scope. Consider a submit button that does something like this:

    function async saveMyStuff(e) {
        const sleeper = new nap(e)
        let data = await fetch(...)
        // a bunch more code.
    }
    
    class nap {
        constructor(e) {
          this.button = e.currentTarget
          this.button.disabled = true
        }
        destructor() { this.button.enabled = true }
    

    }

    This kind of construct would give me a oneliner that handles enabling/disabling all of my buttons when I'm talking to the backend or doing any other processing. I don't have to worry about cleaning up if I return somewhere in the middle or anything like that.

提交回复
热议问题