Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - Error when passing undefined variable to function?

I am trying to create a reusable function that checks if a variable is undefined or not. The strange thing is that it does not work when I pass the variable to the function to execute the code, but if I use the same logic outside of the function, it works. Is there any way to get this function isDefined to work?

//THIS WORKS AND RETURN FALSE
alert(typeof sdfsdfsdfsdf !== 'undefined');

//THIS GIVES AN ERROR, WHY?
//Uncaught ReferenceError: sdfsd is not defined 
function isDefined(value) {
        alert(typeof value !== 'undefined' && value !== null)
}

isDefined(sdfsd);

?Live example here (check the console for errors): http://jsfiddle.net/JzJHc/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot use a variable that hasn't been declared unless it's in a typeof test

When you try to pass a variable that hasn't been declared into a function, that is considered using that undeclared variable. You'll notice that the error is in the caller, not inside isDefined

You need to run the check for

if (typeof sdsdsd !== 'undefined')

before you pass it into the function. Basically that means you can't write a isDefined function that accepts undeclared variables. Your function can only work for undefined properties (which are OK to pass around)

However, I am curious, what is the real world case where you're passing a variable that doesn't exist? You should declare all your variables and they should exist already. Had you declared var sdsdsds it would exist with the value of undefined and your isDefined function would work just fine.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...