How Do Optional Parameters In Javascript Work?
Solution 1:
It goes in order of what was passed to it.
Take the example below,
functiontest(callback) {
var x = 1,
y = 2,
z = 3;
if (typeof callback == 'function')
callback(x, y, z);
}
test(function (z, y, x) {
console.log(z);
});
The output would be,
1
Because in the original code, I passed x
which equals 1
first to the callback
. It doesn't matter what I named it. The functions passed to it are known as callback functions.
Note
Just to explain the typeof
check, I'm checking to see if the passed variable is actually a function, though in this test it is going to be a function, when you use callbacks it is always good to ensure you validate it.
Solution 2:
It does it based on parameter order, and you can't just pass in the second or third parameters by themselves.
In your example, if you pass in one parameter, it's going to be responseTxt
, two parameters will be responseTxt
and statusTxt
. If you want to pass just statusTxt
you would have to pass in a null
for responseTxt
and then your value for statusTxt
.
Solution 3:
Simply, it doesn't, because it assigns each parameter you pass on from your fnction call from left to right. Let's say you have this function, copied from you:
function someFunction(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
alert("External content loaded successfully!");
if(statusTxt == "error")
alert("Error: " + xhr.status + ": " + xhr.statusText);
}
and you want to pass values for variables statusTxt: "success" and xhr: your_xhr when you call this function. If you called the function like this:
someFunction("success", your_xhr);
this means "success" will be assigned to the parameter responseTxt and your_xhr to statusTxt.
Normally, you could just set responseTxt to null and set the rest to what you want, for example:
someFunction(null, "success", your_xhr);
or use an object literal in your function definition. Here's an example:
function someFunction(options){
if(options.statusTxt == "success")
alert("External content loaded successfully!");
if(options.statusTxt == "error")
alert("Error: " + options.xhr.status + ": " + options.xhr.statusText);
}
and your function call would look like this:
someFunction({statusTxt: "success", xhr: your_xhr});
Of course you need to check if responseTxt is undefined in case you don't use it.
Hope this helped.
Solution 4:
This is called callbacks. You dont know for sure that's why you read documentation before using anything. Callbacks can send no response. Or can send a lot of data back. In your case from docs http://api.jquery.com/load/ we have 3 parameters that will be returned. But each library have it's own docs and it's own return results. Hope this helps.
Post a Comment for "How Do Optional Parameters In Javascript Work?"