那个,自我还是我 - 在JavaScript中更喜欢哪一个?

Tör*_*bor 19 javascript naming-conventions this

在编写JavaScript时,有时您会将对象的引用存储this在本地变量中以用于不同目的(设置适当的范围,帮助编写混淆器等).有些编辑喜欢使用别名thisthat明确其意图.其他人使用,self因为它指向对象本身.我甚至看到源代码在哪里me有参考,它仍然有意义.当然还有其他的.

我应该选择哪一个?是否有使用的惯例或仅仅是品味的问题.

bob*_*nce 44

我个人使用that,但其他任何事情都很清楚.

我不会使用self因为全局变量/ window-property self已作为引用存在window.虽然它完全没用(所以没有人可能会关心你的阴影),但它会略微增加愚蠢错误被忽视的风险:

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

然而:

var that= this;
onclick= function() {
    that.foo= 1;        // error thrown
};
Run Code Online (Sandbox Code Playgroud)

有点做作,但JavaScript如此邋with,让错误滑落,你真的不想再这么做了.