0

我看起来很公平,所以如果这已经得到回答,请原谅我。

我也很好奇实际的术语是什么;我正在处理的论点类型是否“模棱两可”?

无论如何,问题是我希望能够调用这样的函数:

prompt(_.define(variable, "DEFAULT VALUE")); 

基本上,这样变量就可以有默认值。

但是,每次我尝试这样做时,都会收到此错误:

Timestamp: 6/11/2012 1:27:38 PM
Error: ReferenceError: thisvarisnotset is not defined
Source File: http://localhost/js/framework.js?theme=login
Line: 12

这是源代码:

function _() {
return this;
};

(function(__) {
__.defined = function(vrb, def) {
    return typeof vrb === "undefined" ? ((typeof def === "undefined") ? null : def) : vrb;
    };
})(_());


prompt(_.defined(thisvarisnotset, "This should work?"), "Can you see this input?");

不知道它为什么这样做?我之前在函数中将未定义的变量称为参数,它工作得很好。

4

2 回答 2

1

完全未声明的变量不能在 JS 中传递;您只能传递已声明的变量或其他变量的未声明属性。

换句话说:

var a; // you can do _.defined(a)
var a = undefined; // you can do _.defined(a)
a.b; // you can do _.defined(a.b), even though we never defined b
于 2012-06-11T17:45:22.047 回答
1

基本上,这样变量就可以有默认值。

为什么不使用默认值初始化变量?

或者,在调用之前初始化变量defined

var variable; // Note that this will not overwrite the variable if it is already set.

或者,甚至更好。

var variable = variable || 'default';
于 2012-06-11T17:51:57.777 回答