简体   繁体   English

用param调用no param javascript函数

[英]Calling a no param javascript function with a param

Does javascript not check function parameters when invoking. 调用时javascript是否不检查功能参数。

This function "test" below fires even though it is being called with no parameter. 即使没有参数调用,下面的该函数“ test”也会触发。

<input type="button" value="test" onclick="test()">

test = function(param){
 alert("test");   
}

fiddle : 小提琴:

http://jsfiddle.net/Yazpj/1912/ http://jsfiddle.net/Yazpj/1912/

Should an error not being thrown or does the javascript engine/parser not even check function parameters when finding what to call. 如果未抛出错误,或者javascript引擎/解析器在查找要调用的内容时甚至不检查函数参数。 Does this have any implications for overriding functions ? 这对覆盖功能有什么影响吗?

No, JavaScript does not check parameters. 否,JavaScript不会检查参数。

Extra parameters will be ignored. 多余的参数将被忽略。 Parameters declared but not passed will have a value of undefined . 已声明但未传递的参数的值将为undefined All passed parameters (declared or otherwise) will appear in the arguments pseudo-array. 所有传递的参数(已声明或其他形式)将出现在arguments伪数组中。

There are no implications for overriding functions because JS does not support overriding functions. 因为JS不支持覆盖功能,所以覆盖功能没有任何意义。

Libraries such as jQuery that have methods with multiple signatures use a single function that figures out the type of the passed parameters and then performs the required action. 具有诸如带有多个签名的方法的jQuery之类的库,使用一个函数来确定所传递参数的类型,然后执行所需的操作。

You have to check on your own: 您必须自己检查:

var test = function (param) {
    if (typeof param === 'undefined') {
        // do something...
    }
};

Javascript is a really flexible language and this is just one example of it. Javascript是一种非常灵活的语言,这只是其中的一个示例。 Unless you are not accessing the param it won t rise any error eg param.sender 除非您不访问param ,否则不会出现任何错误,例如param.sender

As for your override question it is sort of true. 至于您的替代问题,这是对的。 Every Javascript function has a arguments variable which is the array of passed parameters. 每个Javascript函数都有一个arguments变量,它是传递的参数的数组。 if you give name the parameter defining the function JS just give it to you according to order. 如果给名称定义函数JS的参数,只需按照顺序给它。

But overriding is another story the overriding is achieved by checking the arguments element sometimes just length of the array sometimes type of the individual item. 但是,覆盖是另一回事,通过检查arguments元素(有时只是数组的长度,有时是单个项目的类型)来实现覆盖。

For example; 例如; when you call $("#name").val() as there is no item it just return the value if arguments has values this time jQuery user proper assignment eg element.value = arguments[0] 当您调用$("#name").val()因为没有项目,如果参数这次具有jQuery用户适当的赋值,则仅返回值,例如element.value = arguments[0]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM