立即函数:传递可能未定义的参数

时间:2015-03-10 19:18:42

标签: javascript

如何将对象传递给立即函数,而不知道该对象是否已定义?

(function(test) {
    // an exception is thrown: test is not defined.
})(test || {});

3 个答案:

答案 0 :(得分:3)

在访问之前,您需要测试test是否未定义:

(function(test) {

})(typeof(test) == 'undefined' ? {} : test);

答案 1 :(得分:2)

此检查的长期,安全和具体形式将是:

(function(test) {
    // an exception is thrown: test is not defined.
})(typeof test !== 'undefined' ? test : {});

如果变量未定义,则typeof operator不会抛出。

简写等效形式为:

var test = test || {};
(function(test) {
    // an exception is thrown: test is not defined.
})(test);

如果以前没有定义(或者是假的),则定义test。这是有效的,因为标识符在技术上声明为var test但尚未初始化(或覆盖),因此您可以访问先前的值(如果有)或使用未初始化的值。

答案 2 :(得分:1)

如果要检查变量是否存在,可以使用typeof operator

(function(test) {
    // ...
})(typeof test != 'undefined' ? test : {});
相关问题