Apply in Javascript

image After reading an older blog post by Scott Cate, I was curious if the apply function in Javascript would work if no arguments were defined in the calling function.  It turns out that it does work.  Consider the following javascript:





<script type="text/javascript">
    
    function doWithNoArgs() {
        alert (doWithArgs.apply(null, arguments).toString());
    }
    
    function doWithArgs(arg0, arg1, arg2) {
        if (!arg0) arg0=0;
        if (!arg1) arg1=0;
        if (!arg2) arg2=0;
        return arg0 + arg1 + arg2;
    }

    doWithNoArgs(50,500,444);

</script>

The method defined as doWithNoArgs() will execute and recognize the arguments to be passed into the other method (doWithArgs) via the apply function.

The more you know...

Technorati Tags: ,

1 Comment

  • If I was paying attention to all the Silverlight Javascript in the host page script of the VS2008 template, I would have had the answer there too:

    Silverlight.createDelegate = function(instance, method) {
    return function() {
    return method.apply(instance, arguments);
    }
    }

    The above script defines a function() with void of args.

Comments have been disabled for this content.