javascriptapiwebkitv8sfx

invalid JavaScript signature still calls correct API


why does this work ?

<html>
<body id = "body">
<div id="para">hello world, invalid js API signature doesn't throw error !!!</div>
<script>
var temp = document.getSelection("parameter");
</script>
</body>
</html>

getSelection() does not take any parameter as per standard signature. I have tested this and it does not throw any error on JS console either.


Solution

  • JavaScript doesn't complain if you call a function with the wrong number of arguments. If there are fewer arguments passed than declared, the extra parameters have the value undefined. If there are more, they are simply ignored. This is a feature and not a bug!

    Inside the JavaScript function you have access to the arguments value which is an array-like structure holding all the arguments passed to it. If you wanted you could define all your functions to take 0 parameters and use arguments[0], arguments[1], etc instead of the named parameters you previously had (though i don't see why one would do that) and the functions would still work exactly the same.

    The benefits of having this arguments structure and no limits on how many arguments you call a function with allows you to do very powerfull things, like the bind polyfill found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind