Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

library function for safe property reference on javascript objects

Tags:

javascript

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.

like image 840
Adrian Herscu Avatar asked Oct 22 '12 14:10

Adrian Herscu


People also ask

How can you read properties of an object in JavaScript?

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.

What is $() in JavaScript?

$() 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.

What is object referencing in JavaScript?

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.

Is there a JavaScript standard library?

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.


1 Answers

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.

like image 118
ArtoAle Avatar answered Oct 13 '22 00:10

ArtoAle