【问题标题】:Undefined variable as function argument javascript未定义的变量作为函数参数javascript
【发布时间】: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


【解决方案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

【讨论】:

  • 要修复你的代码,一种选择是一直这样做 "window.thisvarisnotset";由于 window 是全局范围,因此应该可以。当然,值得一提的是,您几乎是在尝试在这里创建一个新的 JS 变体;祝其他必须使用您的代码的人好运。
  • 如果thisvarisnotset没有在别处声明,则引用window.thisvarisnotset。但这并不能解决问题。
  • 哦,好点。是的,你真的想改变JS,那是做不到的。正如 ddlshack 所提到的,更多的 JS-ish 解决方案是在任何地方都执行“thisvarisnotset || defaultValue”,而不是尝试定义一个像您要创建的函数那样的函数。
  • (嗯,甚至更多的 JS-ish 解决方案是重构你的代码,使其不依赖于首先声明的模棱两可的变量......)
  • (... foo || 默认模式很有用,您会发现它在 jQuery 等主要库中使用,但您应该只在少数特定情况下需要它;不是那么多你觉得你需要做一个函数。如果你确实觉得你非常需要它,那么可能有更好的方法来完成你想要完成的事情。)
【解决方案2】:

基本上,让变量可以有默认值。

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

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

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

或者,甚至更好。

var variable = variable || 'default';

【讨论】:

    猜你喜欢
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    相关资源
    最近更新 更多