Undefined variable as function argument javascript

☆樱花仙子☆ 提交于 2019-12-20 06:48:37

问题


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.


回答1:


A completely undeclared variable can't be passed in JS; you can only pass declared variables or undeclared properties of other variables.

In other words:

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



回答2:


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';


来源:https://stackoverflow.com/questions/10984927/undefined-variable-as-function-argument-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!