未定义的变量作为函数参数javascript [英] Undefined variable as function argument javascript

查看:213
本文介绍了未定义的变量作为函数参数javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看得很好,所以赦免我已经得到回答了。



我也很好奇实际的名字叫什么;
我正在处理的参数类型是否不明确?



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

  prompt(_。define(variable,DEFAULT VALUE)); 

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



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

  Timestamp:6/11/2012 1:27:38 PM 
错误:ReferenceError:未定义thisvarisnotset
源文件:http://localhost/js/framework.js?theme = login
行:12

这是源代码:

  function _(){
return this;
};

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


提示(_。defined(thisvarisnotset,这应该工作?),你能看到这个输入吗);

不知道为什么这样做?我已经将未定义的变量称为函数中的参数,它的工作正常。

解决方案


,所以变量可以有默认值。


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



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

  var variable; //请注意,如果已经设置了该变量,则不会覆盖该变量。 

或者更好。

  var variable = variable || '默认'; 


I've looked a fair bit, so pardon me if this has already been answered.

I'm also curious as to what the actual term is called; Is it "Ambiguous" for the type of arguments I am handling?

Anyways, the problem is that I want to be able to call a function like this:

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

Basically, so that variables can have default values.

However, every time I try to do this, I get this error:

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

Here is the source code:

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

Not sure why it's doing this? I've called undefined variables as arguments in functions before and it worked just fine.

解决方案

Basically, so that variables can have default values.

Why don't you just initialize the variable with a default value?

Or, just initialise the variable before calling defined.

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

Or, even better.

var variable = variable || 'default';

这篇关于未定义的变量作为函数参数javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆