【发布时间】:2012-06-11 17:40:52
【问题描述】:
我看起来还不错,如果这个问题已经得到回答,请原谅我。
我也很好奇实际的术语叫什么; 我正在处理的参数类型是否“模棱两可”?
无论如何,问题是我希望能够调用这样的函数:
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?");
不知道为什么会这样?我之前在函数中调用了未定义的变量作为参数,它工作得很好。
【问题讨论】:
-
是的,你不能在 javascript 中这样做。
-
variable = variable || 'default'; -
var variable = variable || 'default';会更好,因为您还不知道变量是否已初始化。否则,您将在全局范围内初始化variable。 -
谢谢,这让事情比我之前做的(var || 'default')更简单了。我不知道您不能以这种方式传递未定义的变量,我认为该函数会自动将其分配为未定义的。谢谢!
标签: javascript function error-handling undefined ambiguous