未定义的变量作为函数参数 javascript

Undefined variable as function argument javascript

本文关键字:函数 参数 javascript 变量 未定义      更新时间:2023-09-26

我已经看了不少,所以如果这个问题已经回答了,请原谅我。

我也很好奇实际的术语叫什么;对于我正在处理的论点类型来说,它是"模棱两可的"吗?

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

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?");

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

完全未声明的变量不能在 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

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

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

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

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

或者,甚至更好。

var variable = variable || 'default';