Questions about function signature
I found a javascript example online that made me a bit confused. I’m quite new to javascript but have good knowledge in “traditional” languages. I 开发者_Python百科was not able to find an answer when I tried google for it so I’ll ask the question here and hope someone can help me.
From one "class" the following code was executed:
this.foo.addListener("xType", this, this.boo);
The function that were called looked like this:
//first argument (type:String) what kind of event
//second argument (type:Function) listener - listening function
addListener: function(kindOf, listener) {
What I don't understand is that the number of arguments does not match. When the function is called 3 arguments are used namely "xType", this and this.boo but in the function signature there is only 2 arguments namely kindOf and listener. Is this some javascript functionality that you can call functions with some other amount of arguments than what is declared in the function? Or how is this code supposed to work?
Is this some javascript functionality that you can call functions with some other amount of arguments than what is declared in the function?
This is correct. JavaScript does not require that you call a function with the same number of arguments as was used to define it.
If you call it with too few, the missing values will have the special value undefined
. If you call it with too many, the function will need to use the special array value arguments
to get at them. For example,
function alertMany() {
for (var i = 0; i < arguments.length; i++) {
alert(arguments[i]);
}
}
alertMany("hello", "goodbye");
alertMany("hello", "hello again", "hello once more", "farewell");
alertMany()
All of these calls will work, displaying up one alert box for each argument.
In javascript you can build functions on fly.
The line:
addListener: function(kindOf, listener) {
is adding a function with to argument to an object. You should find a code that transforms that to a function with 3 arguments.Eg: a loop that walks through the object and creates functions based on this on the fly. This is pretty common for a couple of frameworks (especially jquery).
Alternatively you are looking at the wrong definition, and the actual code is elsewhere.
In ES6 you can now use the rest parameter to pass an arbitrary amount of arguments to a function signature:
const addUs = (x, y, ...z) => <your function here>
精彩评论