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

javascript - Why does google main page use (0, obj.func)(args) syntax?

Sometimes I stared at js provided with google.com main page and found that they tended to use (0, obj.func)(args) syntax. Here are excerpts from the script:

 var _ = _ || {};
 (function (_) {
     var window = this;
     try {
         _.mb = function (a) {
             return (0, window.decodeURIComponent)(a.replace(/+/g, " "))
         };
         _.zg = function (a, b) {
             for (var c = a.length ? a.split("&") : [], d = 0; d < c.length; d++) {
                 var e = c[d];
                 if ((0, _.Ag)(e) == b) return (c = /=(.*)$/.exec(e)) ? (0, _.mb)(c[1]) : null
             }
             return null
         };
         _.Ag = function (a) {
             return (a = /^(.+?)(?:=|$)/.exec(a)) ? (0, _.mb)(a[1]) : null
         };
         var Cg = function (a, b) {
                 var c = a.indexOf("?");
                 return 0 > c ? null : (0, _.zg)(a.substring(c + 1), b)
             };
         // Note var Cg called with no 0
         var oca = function (a) {
                 this.A = Cg(a, "mods");
                 this.B = Cg(a, "ver")
             };
     } catch (e) {}
 })(_);  

Why prepending 0?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This makes an indirect call.

This ensures the context, in the called function, is the global one. This might be useful in an internal scope.

Example :

var a = {
  b: function(){
     console.log(this);    
  },
  c1: function(){
     this.b(); 
  },
  c2: function(){
     (0, this.b)(); 
  },
  c3: function(){
     (this.b)(); 
  }
}
a.c1(); // logs a
a.c2(); // logs window
a.c3(); // logs a

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

...