Javascript equivalent of Rails try method

后端 未结 6 793
醉话见心
醉话见心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 02:23

    You can do this way, as there is no built in way of doing that:

    var x = (user || {}).name;
    
    • If user is not defined/null you will get undefined
    • If user is defined you will get the name property (which may be set or undefined).

    This won't break the script if user is not defined (null).

    But user variable has to be declared some where in the scope, even though its value is not defined. Otherwise you will get the err saying user is not defined.

    Similarly if is in global scope then you can explicitly check for this variable as a property of global scope, to avoid the error as mentioned above

    ex:

     var x = (window.user || {}).name; // or var x = (global.user || {}).name;
    

    For safe execution of functions,

     var noop = function(){}; //Just a no operation function
    
     (windowOrSomeObj.exec || noop)(); //Even if there is no property with the name `exec` exists in the object, it will still not fail and you can avoid a check. However this is just a truthy check so you may want to use it only if you are sure the property if exists on the object will be a function.
    

提交回复
热议问题