Javascript equivalent of Rails try method

后端 未结 6 796
醉话见心
醉话见心 2021-02-05 01:56

In Rails I can do this:

 x = user.try(:name)

this method returns nil if user is nil else user.name

6条回答
  •  醉话见心
    2021-02-05 02:30

    In Rails4, try does this:

    Invokes the public method whose name goes as first argument just like public_send does, except that if the receiver does not respond to it the call returns nil rather than raising an exception.

    In Rails3, try is like try! in Rails4 and that's the same as try except that it complains if the object doesn't understand the method you're trying to call. The original intent of try was to hide a bunch of nil checks so that you could say:

    o.try(:m)
    

    instead of

    o.nil?? nil : o.m
    

    The Rails4 version also hides a check if the object understands the method you want to call.

    There's no special syntax for this in JavaScript but you can sweep the ugliness into a function.

    The Rails4 version of try would look like this function in JavaScript:

    function rtry(obj, m) {
        if(obj == null)
            return null;
        if(typeof obj[m] === 'function')
            return obj[m].apply(obj, [].slice.call(arguments, 2));
        return null;
    }
    

    and you'd say things like x = rtry(obj, 'method_name', arg1, arg2, ...) and x would be null if obj didn't understand method_name (including if obj is null or undefined).

    Demo: http://jsfiddle.net/ambiguous/BjgjL/

    A Rails3 version is simple, that's just a null check:

    function rtry(obj, m) {
        if(obj == null)
            return null;
        return obj[m].apply(obj, [].slice.call(arguments, 2));
    }
    

    and JavaScript itself will raise an exception of obj doesn't have an m method. This version is equivalent to the "is it a function" version of CoffeeScript's ? existential operator.

    Demo: http://jsfiddle.net/ambiguous/FQCS2/


    As usual, things might not work out so well if you're dealing with native methods rather than methods that you've written in JavaScript. typeof (6).toString might be 'function' in one JavaScript environment but I don't think it is guaranteed to always be 'function' everywhere. The primary use (i.e. hide null and undefined checks) should work everywhere though.

提交回复
热议问题