那个,自我还是我 - 在JavaScript中更喜欢哪一个? [英] that, self or me — which one to prefer in JavaScript?

查看:101
本文介绍了那个,自我还是我 - 在JavaScript中更喜欢哪一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 obfuscators, etc.). There are coders who prefer aliasing this to that to make it obvious its intention. Other guys use self since it's pointing to the object itself. I even saw source codes where me held the reference and it still makes sense. Certainly there are other ones.

我更喜欢哪一个?是否存在可以使用的惯例,或者仅仅是品味问题。

Which one should I prefer? Is there a convention on which to use or is it only the matter of taste.

推荐答案

我个人使用那个,但其他任何明确的东西都没问题。

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

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

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`!
};

而:

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

有点做作,但是JavaScript很邋with,让错误滑动你真的不想让它变成任何更多。

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

这篇关于那个,自我还是我 - 在JavaScript中更喜欢哪一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆