未定义的变量作为函数参数 javascript
Undefined variable as function argument javascript
我已经看了不少,所以如果这个问题已经回答了,请原谅我。
我也很好奇实际的术语叫什么;对于我正在处理的论点类型来说,它是"模棱两可的"吗?
无论如何,问题是我希望能够调用这样的函数:
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';
相关文章:
- 函数参数中的数据与指定变量之间的任何性能差异
- AngularJS:我可以跳过函数参数回调吗
- 为什么不'我们在javascript中使用函数参数的数据类型
- 使用闭包共享构造函数参数
- 函数参数的值错误
- 当一个重要的构造函数参数丢失时应该发生什么
- 阻止ReSharper将JavaScript函数参数放到新行中
- 根据函数参数将CSS值存储在var中,然后对其进行操作
- 使构造函数参数具有ES6类方法的特权
- 当客户端将两个按钮的javascript函数参数修改为相同时,SQL/PHP会更新多行
- Windows.Networking.EndpointPair构造函数参数
- 是否可以使用Sinon.JS检查函数参数绑定是否正确
- 大括号中的Javascript函数参数
- jQuery 无法使用 AJAX 调用访问函数内部的函数参数
- 将JSON字符串转换为函数参数
- eval()读取函数参数有多糟糕
- Javascript不能在一个命令中使用函数参数
- 函数参数在内部不可见,返回新的Promise(函数(resolve,reject).传递给被promise化的函数的
- ES6类构造函数参数
- 是否可以在javascript函数参数列表中调用多个函数