Javascript: passing a not defined variable to a function

你离开我真会死。 提交于 2019-12-09 03:46:19

问题


I have some calls to AJAX where I return a JSON object as a response. This JSON object always has the same structure. However, there are sometimes where if the PHP scripts fails, some of the objects of the JSON structure are not defined or even inexistent.

This also happens with some "global" variables that are present in a page and I use in some JS files, but then go to another page where I use those JS files and the variable is not even written.

So, I thought to create a function is_defined() to which I could ask if a variable is defined or not. The function is as the following:

function is_defined(ob, can_empty){
    if(can_empty === undefined || can_empty == '') can_empty = false

    return ob !== undefined && ob !== null && (ob !== '' || can_empty)
}

So, if the variable passed is NULL or undefined, or it's empty (and it cannot be empty), I return false.

My problem comes when the variable is not even written, as I cannot pass it to the function because an Uncaught ReferenceError: obj is not defined error is raised.

So my question is if is there any way to create a function to check if a variable exists and is defined, as I'd like to centralize all these checks into a function and not writing obj !== undefined || obj !== null every now and then on my code.

I thought that with a double Not operator (!!!obj) would cast to false, but I face the same problem if the variable is not written.

EDIT: Just as an aclaration, the issue here is to be able to do the checks for undeclared and undefined variables inside a function, so I can pass a variable to the function without having to check it before calling it if the variable is declared or not.

Thank you all for your time and answers!

Kind regards!


回答1:


[...] is there any way to create a function to check if a variable exists and is defined [...]

No there is not. When you pass a variable to a function, it will always try to resolve that variable. If it is not declared it will throw a reference error.

Relevant section from the ECMAScript specification.

You have to check whether the variable is declared via typeof before you pass it to a function.




回答2:


You can use typeof variableName === 'undefined' to test if the variable is even declared.

Specifically:

  • typeof variable === 'undefined' tests if the variable is declared.
  • variable === undefined tests if the declared variable is defined or assigned any value.



回答3:


Foolproof way to check for an existing variable:

typeof variableName === 'undefined'



来源:https://stackoverflow.com/questions/28611192/javascript-passing-a-not-defined-variable-to-a-function

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