user1038662
user1038662

Reputation: 69

Who can give me about this grammar in javascript

function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
    ud = 'json' + (+new Date());
window[ud]= function(o){
    success && success(new Date(o.datetime), o);
};
document.getElementsByTagName('head')[0].appendChild((function(){
    var s = document.createElement('script');
    s.type = 'text/javascript';
    s.src = url + '&callback=' + ud;
    return s;
})());}

What is the use of window[ud] and what does success && success() mean? Another question is why we need an extra pair of brackets in the last line when calling appendChild outside its anonymous function?

Upvotes: 2

Views: 149

Answers (3)

Ry-
Ry-

Reputation: 224942

success && success(...) basically means "if success exists, call success()." It's equivalent to the following:

if(success) {
    success(new Date(o.datetime), o);
}

window[ud] means "the property of window named ud." So if ud were (for example) "json12341234" then it would be equivalent to window.json12341234.

The extra pair of parentheses calls the anonymous function. So instead of passing that function, you're passing the result.

Upvotes: 6

Igor Dymov
Igor Dymov

Reputation: 16460

  1. success && success(...) means that success might be a function and if it passed to the function it will be called with new Date(o.datetime), o
  2. extra pair of brackets is for immediate function call, which is inside the brackets
  3. window[ud] might be replaced with window.ud - global variable definition

Upvotes: 0

deviousdodo
deviousdodo

Reputation: 9172

window[ud] is a callback that's going to called automatically by the JSON-P Javascript that's going to come in from the XMLHttpRequest.

success&&success() is a shortcut for if (success) { success(); }.

The extra pair of brackets mean that the anonymous function will be called directly, in effect meaning that appendChild will actually be called with the anonymous function's returned value instead of the function itself.

Upvotes: 0

Related Questions