SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    May 2010
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    the call method in JavaScript

    Hey all,

    I'm confused as to why the call method is being used here. We call it on slice, which itself is a method of Array. And we pass in, not an object, but a bunch of arguments stored in arguments. So it's not like we are trying to use "this" for something else. We are just dealing with arguments passed into the constructor. So why is call used here? Why couldn't we just use Array.prototype.slice(arguments)?

    Code:
    function Core(){
    	var args = Array.prototype.slice.call(arguments)
            //...
    }
    
    Core(['dom','event','ajax'],function(box){
         //...
    })
    Thanks for response

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,718
    Mentioned
    103 Post(s)
    Tagged
    4 Thread(s)
    The arguments variable is an array-like object. By passing arguments to the array's slice method, that slice method gives you a real true array.

    Effectively, you're converting an array-like object in to a proper array.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Enthusiast
    Join Date
    May 2010
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    But why is the call method here necessary?

    Thanks for response.

  4. #4
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by JohnMerlino View Post
    But why is the call method here necessary?

    Thanks for response.
    Code JavaScript:
    function Core(){
        console.log(typeof arguments);//Object
        console.log(arguments instanceof Array);//false
        var args = arguments.slice(0); //arguments.slice is not a function
    }
    Core('dom','event','ajax');

  5. #5
    SitePoint Enthusiast
    Join Date
    May 2010
    Posts
    28
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    understood, thanks.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •