Consider the following code:
function foo(handlers) {
callSomeFunction(handlers.onSuccess, handlers.onFailure);
}
The caller may do:
foo({onSuccess: doSomething, onFailure: doSomethingElse });
or simply just
foo()
if s/he has nothing special to do.
The issue with the above code is that if 'handlers' are undefined, like in the simple foo() call above, then a run-time exception will be thrown during the execution of callSomeFunction(handlers.onSuccess, handlers.onFailure).
For handling such situations one may re-write the foo function as:
function foo(handlers) {
var _handlers = handlers || {};
callSomeFunction(_handlers.onSuccess, _handlers.onFailure);
}
or more structured
function safe(o) {
return o === Object(o) ? o : {};
}
function foo(handlers) {
callSomeFunction(safe(handlers).onSuccess, safe(handlers).onFailure);
}
I tried to find something like the safe() function in libraries such as sugarjs and underscore, but found nothing. Did I miss something? Is there any other utility library that has a similar function?
Just trying not to reinvent the wheel... ;)
BR, Adrian.
P.S. I didn't test the code above, so it may have errors.
We can use the jQuery library function to access the properties of Object. jquery. each() method is used to traverse and access the properties of the object.
$() The $() function is shorthand for the getElementByID method, which, as noted above, returns the ID of a specific element of an HTML DOM. It's frequently used for manipulating elements in a document.
In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.
The JavaScript language does not have a standard library. As a result new functionality is added to the global object, or developers find and adopt libraries that they bundle with the rest of their application.
There is something pretty similar in jQuery, often used when dealing with plugin development wich is jQuery.extend:
function foo(options){
var defaults = {onSuccess: someFunction, onFailure: someOtherStuff}
var options = $.extend({}, defaults, options);
}
In this case it make sense, because user can provide an arbitrary subset of options, and the function with add the defaults for those not provided in the function call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With