In ECMAScript 5 and earlier, you would likely use the following pattern to accomplish Default Parameters:
function makeRequest(url, timeout, callback) {
timeout = timeout || 2000;
callback = callback || function() {};
// the rest of the function
}
In this example, both timeout and callback are optional .
ECMAScript 6 makes it easier to provide default values for parameters by providing initializations that are used when the parameter isn’t formally passed. For example:
function makeRequest(url, timeout = 2000, callback = function() {}) {
// the rest of the function
}
//-----------------------------------
// uses default timeout and callback
makeRequest("/foo");
// uses default callback
makeRequest("/foo", 500);
// doesn't use defaults
makeRequest("/foo", 500, function(body) {
doSomething(body);
});
It’s possible to specify default values for any arguments, including those that appear before arguments without default values.
function makeRequest(url, timeout = 2000, callback) {
// the rest of the function
}
//--------------------------
// uses default timeout
makeRequest("/foo", undefined, function(body) {
doSomething(body);
});
// uses default timeout
makeRequest("/foo");
// doesn't use default timeout
makeRequest("/foo", null, function(body) {
doSomething(body);
});
Good thing is default value need not be a primitive value.
function getCallback() {
return function() {
// some code
};
}
function makeRequest(url, timeout = 2000, callback = getCallback()) {
// the rest of the function
}
No comments:
Post a Comment