是否可以在Javascript中将未声明的变量作为参数传递? [英] Is it possible to pass undeclared variables as parameters in Javascript?

查看:83
本文介绍了是否可以在Javascript中将未声明的变量作为参数传递?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个变量 myvar ,而我有一个变量 myvar2 。我可以毫无问题地运行以下内容:

Let's say I have a variable myvar, and I don't have a variable myvar2. I can run the following without a problem:

typeof myvar
// ⇒ 'string'
typeof myvar2
// ⇒ 'undefined'

typeof delete 是我所知道的唯一一个在给定未定义参数时不会抛出错误的函数。我查看了 类型的语言规范 和我不熟悉的眼睛似乎使用内部函数,如 IsUnresolvableReference

typeof and delete are the only functions I know of which don't throw errors when given an undefined parameter like this. I looked at the language spec for typeof and to my uninitiated eyes it seems to use internal functions like IsUnresolvableReference.


编辑:我一直在使用一个同义函数,并没有注意到 typeof 实际上是JavaScript中的运算符。我从这里的代码中删除了括号,但是上面写了上面的内容。

Edit: I'd been working in a language that checks type with a synonymous function, and hadn't noticed typeof is actually an operator in JavaScript. I've removed parentheses from the code here but left the above as written.

当我创建一个函数时:

function myFunc(input_variable) {
  return("hello");
}

...按预期抛出 ReferenceError 当传递 myvar2 作为参数时,除非我运行 var myvar2;

... as expected this throws a ReferenceError when passed myvar2 as a parameter, unless I run var myvar2;.

如果我将回报换成尝试 / catch 语句来处理在 myvar2未定义的情况下,我仍然得到相同的错误,因为在进入函数时,似乎要检查变量的可解析引用(在运行时?):

If I wrap the return in a try/catch statement to handle the myvar2 not defined case, I still get the same error, as the variable seems to be checked for a resolvable reference upon entry into the function (upon runtime?) :

function myFunc(input_var) {
  try {
    return "hello";
  } catch(error) {
    if (error.name === 'ReferenceError'){
      return "world";
    }
  }
}

我想知道我怎么做创建一个接受未解析引用的函数。我的一般猜测是,如果它是函数的标准行为,那么也许我可以专门修改这个结构的一些原型......?我知道原型是用于对象的,我想知道是否可以以某种方式对函数进行这种控制?

I was wondering how I can make a function that accepts unresolved references. My general guess is that, if it's a standard behaviour of functions, then perhaps I could modify some prototype for this construction specifically...? I'm aware prototypes are for objects, I'm wondering if this level of control over function is possible somehow?

通过上下文,我总是发现自己写函数(input_var)

By way of context, I always find myself writing function(input_var) :

if (typeof input_var == 'undefined' || my_settings.input_var_is_optional === true)
  var input_var = 'Sometimes variables are optional. This is my default value.';
  return dealWith(input_var);
} else if (typeof input_var == 'string') {
    return dealWith(input_var);
} else {
  // Already checked that input_var isn't optional, so we have a problem
  return false; // or throw a TypeError or something like that
}

但是所有这些的冗长plain让我无法在我的代码中写入类型检查,使得更自由地使用函数变得不那么健壮,或者传递给其他开发人员。

but the verbosity of all that plain puts me off writing type checking into my code, making it less robust to use functions more freely, or to pass onto other developers.

我想写一个类型处理函数,例如

I'd like to write a type handling function, e.g.


对于函数 myFunc(input_var) ,如果已经定义了作为参数 input_var 传入的变量,请检查它是否为字符串,否则将其设置为 DEFAULT_VALUE。如果没有定义,也将其设置为default_value,否则它是一个有效的字符串,所以只需使用 input_var 按原样。

For a function myFunc(input_var), if the variable passed in as parameter input_var has been defined, check if it's a string, else set it as "default_value". If it wasn't defined, also set it as "default_value", else it's a valid string, so just use input_var as is.

...但是由于我实际上无法传递任何内容而受到破坏未定义,有效地阻止我在一个单独的函数中隔离这个复杂性,我可以传递2个参数: input_var (真正的交易,不仅仅是它的名字),以及 expected_type

...but it's sabotaged by the fact that I can't actually pass anything in that's undefined, effectively stopping me from isolating this complexity in a separate function to which I could just pass 2 parameters: input_var (the real deal, not just its name), and expected_type.

function typeTest(input_var, expected_type) {
  var is_optional_value = (typeof expected_type != 'undefined'
                                                 && expected_type === true);
  var optional_str = is_optional_value ? "|(undefined)" : ''
  var type_test_regex = RegExp('^(?!' + expected_type + optional_str + '$)');
  var is_expected_type = type_test_regex.test(typeof(input_var));
}

例如,要检查传递给函数的可选变量是否已定义,并被定义为一个字符串,

For example, to check that an optional variable passed into a function was both defined, and was defined as a string,

var myvar = 'abc'
//  myvar2 is never defined

// Mandatory type (expecting a string):
typeTest(myvar, 'string'); // true
// if (/^(?!string)$)/.test(typeof(myvar))
typeTest(myvar2, 'string'); // throws error

// Mandatory type (expecting a number):
typeTest(myvar, 'number'); // false
typeTest(myvar2, 'number'); // throws error

// Optional type ("expected is true"):
typeTest(myvar, true); // true
// if (/^(?!string|(undefined)$)/.test(typeof(myvar))
typeTest(myvar2, true); // throws error


推荐答案


我想知道如何制作接受未解析引用的函数。

I was wondering how I can make a function that accepts unresolved references.

你不能。当你访问未声明的变量时, ReferenceError 在函数被调用之前发生。函数内部没有任何东西可以从中恢复,因为它甚至没有被调用。

You can't. When you access an undeclared variable, the ReferenceError occurs before the function even gets called. There's nothing you can do inside the function to recover from this, because it hasn't even been called.

typeof和delete是我所知道的唯一一个在给定未定义参数时不会抛出错误的函数。

typeof and delete are the only functions I know of which don't throw errors when given an undefined parameter like this.

typeof delete 不是函数。这就是原因。

typeof and delete are not functions. That's why.


例如,检查传递给函数的可选变量是否已定义,并定义为字符串。

For example, to check that an optional variable passed into a function was both defined, and was defined as a string.

没有什么可以阻止你这样做。以下是:

There's nothing stopping you from doing this. There is a difference between:


  • 值为 undefined的变量

  • 尚未传递值的参数

  • 未声明的变量。

处理前两个问题没有问题:

There is no problem in dealing with the first two:

function hasType(val, type) {
  return typeof val === type;
}

function myFunc(param1, param2) {
  console.log('param1: ', hasType(param1, 'string'));
  console.log('param2: ', hasType(param2, 'string'));
}

myFunc('hello');

无需检查是否有人试图使用未声明的变量调用您的函数。如果是,那么问题在于他们的代码,他们需要修复它。如果他们正在利用可选参数,这是另一回事,您可以正好处理该场景。

There is no need to check whether someone is trying to call your functions with undeclared variables. If they are, then the problem is with their code and they need to fix it. If they are taking advantage of optional parameters, that is a different matter, and you can handle for that scenario just fine.

这篇关于是否可以在Javascript中将未声明的变量作为参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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