0

I check to see if NS.ajax exists. If so I do not need to redefine it. If it does not exist I redefine it.

I want to verify that this does what I think it does and I don't waste time interpreting the function below if I already have NS.ajax defined.

NS.ajax is the same as the anonymous function seen below.

Can someone verify?

/*ajax ** ** ** */ $P.ajax = (function () { if (NS.ajax) { return NS.ajax; } return function (config) { var xhr; if (config.type === 'get') { xhr = new window.XMLHttpRequest(); xhr.open('GET', config.url, true); xhr.onreadystatechange = function () { if (this.readyState === 4) { if (this.status === 200) { config.callback(xhr.responseText); } else { return false; } } }; xhr.send(null); return; } }; }()); 
2
  • What happens when you try it? Commented Mar 4, 2013 at 20:59
  • This will set $P.ajax to a function. If NS.ajax exist that will be returned, otherwise an anonymous function will be. Commented Mar 4, 2013 at 20:59

2 Answers 2

2

Just do:

$P.ajax = NS.ajax || (function () { ... }); 
Sign up to request clarification or add additional context in comments.

2 Comments

@pure_code: just FYI - when the || operator evaluates, it returns the first truthy value it finds and stops evaluating further. undefined is falsey, so if NS.ajax in undefined it continues to evaluate the right-hand-side of the || and finds the function definition, which is truthy, and returns it.
That's correct! It returns the whole truthy value (the function) rather that a boolean representing it's truthy-ness. This is what you want, I just thought I'd try to explain what's happening :)
1

You can return NS.ajax or your own function in the same line.

return NS.ajax || function (config) {... 

Comments