that, self or me — which one to prefer in JavaScript?

前端 未结 3 937
挽巷
挽巷 2020-12-16 12:31

While coding JavaScript sometimes you store the reference of object this in a local variable for different purposes (to set proper scope, to help code obfuscato

3条回答
  •  不思量自难忘°
    2020-12-16 12:42

    I, personally, use that, but anything else that's clear is fine.

    I wouldn't use self because the global variable/window-property self already exists as a reference to window. Although it's totally useless (so no-one is likely to care that you're shadowing it), it slightly increases the risk of silly errors going unnoticed:

    var se1f= this;         // misspelled (perniciously). or maybe you just forgot to write line
    onclick= function() {
        self.foo= 1;        // whoops, just wrote to `window`!
    };
    

    whereas:

    var that= this;
    onclick= function() {
        that.foo= 1;        // error thrown
    };
    

    Slightly contrived, but JavaScript's so sloppy with letting errors slide you don't really want to make it any more so.

提交回复
热议问题