それを行う方法が組み込まれていないため、次の方法で行うことができます。
var x = (user || {}).name;
- ユーザーが定義されていない/nullの場合、未定義になります
- user が定義されている場合、name プロパティを取得します (設定または未定義の場合があります)。
ユーザーが定義されていない (null) 場合、これはスクリプトを壊しません。
ただし、ユーザー変数は、その値が定義されていなくても、スコープ内のどこかで宣言する必要があります。そうしないと、ユーザーが定義されていないというエラーが表示されます。
同様に、 がグローバル スコープ内にある場合、上記のエラーを回避するために、この変数をグローバル スコープのプロパティとして明示的にチェックできます。
元:
var x = (window.user || {}).name; // or var x = (global.user || {}).name;
機能を安全に実行するために、
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.