Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
419 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...