假设我有一个变量myvar
, and I don't有一个变量myvar2
。我可以毫无问题地运行以下命令:
typeof myvar
// ⇒ 'string'
typeof myvar2
// ⇒ 'undefined'
typeof
and delete
这是我所知道的唯一在给定像这样的未定义参数时不会抛出错误的函数。我在看语言规范typeof http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.3在我外行看来,它似乎使用了内部函数,例如IsUnresolvableReference
.
Edit: I'd been working in a language that checks type with a synonymous function https://stat.ethz.ch/R-manual/R-devel/library/base/html/typeof.html, 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;
.
如果我将退货包裹在try
/catch
声明来处理myvar2 未定义在这种情况下,我仍然遇到相同的错误,因为变量似乎在进入函数时检查可解析的引用(在运行时?):
function myFunc(input_var) {
try {
return "hello";
} catch(error) {
if (error.name === 'ReferenceError'){
return "world";
}
}
}
我想知道如何创建一个接受未解析引用的函数。我的一般猜测是,如果这是函数的标准行为,那么也许我可以专门修改此构造的一些原型......?我知道原型是针对对象的,我想知道这种级别的控制是否function
有可能吗?
通过上下文,我总是发现自己在写作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
}
但是所有这些简单的冗长让我无法在代码中编写类型检查,从而使更自由地使用函数或传递给其他开发人员的功能变得不那么健壮。
我想写一个类型处理函数,e.g.
对于一个函数myFunc(input_var)
, 如果变量作为参数传入input_var
已定义,检查它是否是字符串,否则将其设置为"default_value"
。如果没有定义,也将其设置为"default_value"
,否则它是一个有效的字符串,所以只需使用input_var
as is.
...但事实是,我实际上无法传递任何未定义的内容,这实际上阻止了我将这种复杂性隔离在一个单独的函数中,我只能向该函数传递两个参数:input_var
(真正的交易,不仅仅是它的名字),以及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));
}
例如,要检查传递给函数的可选变量是否已定义,并且已定义为字符串,
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