Last Updated: February 25, 2016
·
678
· nickjacob

Safely call nested methods

Want to call a nested method on an object without having to worry about causing an error (like coffeescript's existential operator, ?)

// mthd: full path to method, args - array of arguments
myObj.prototype.callnested = function(mthd,args){
    var m = mthd.split('.'),o=this;
    for(var i=0,l=m.length; i < l; i++){
        if(o[m[i] === void(obj = o[m[i]])) return void(0);
    }
    return o.apply(this,args);
}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#javascript
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside