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
337 views
in Technique[技术] by (71.8m points)

javascript - What's the reason for using such syntax (0, _.Em)();

While investigating google plusone scripts, I've seen following syntax many times:

(0, _.Em)();

Assuming _.Em is a function the statement above would result in calling that function, that's pretty obvious. If, on the other hand, it would be undefined, wouldn't the result be the same as doing simply _.Em() ?

Can anyone shed a light on what's idea behind using such syntax?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Basically, this syntax allows to call _.Em() in the context of the window object instead of _.

Assuming you have this code:

Foo = function() {
    this.foo = "foo";
};

Foo.prototype.Em = function() {
    alert(this.foo);
};

var _ = new Foo();

Issuing _.Em() will result in Em() being called in the context of _. Inside the function, the this keyword will refer to _, so foo will be printed.

Issuing (0, _.Em)() decouples the method call from the object and performs the call in the global context. Inside the function, the this keyword will refer to window, so undefined will be printed, since window does not have a foo property.

You can test the difference between the two syntaxes in this fiddle.


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

...