hh54188
hh54188

Reputation: 15626

Confuse about javascript function's call method

I read an article about how speed up javascript, I try copy it's code which could improve loop speed:

var chunk = function (array, process, context) {
        setTimeout(function(){  
            var item = array.shift();  
            console.log('item', item);//this could show correctly
            process.call(item, context);  

            if (array.length > 0){  
                setTimeout(arguments.callee, 100);  
            }  
        }, 100); 
    }

Then I try to pass my parameter into it, but I don't know how to use the context parameter, what I have done is:

  var dosomething1 = function (item) {
      console.log('this is begin ' + item)
  }

  var dosomething2 = function (item) {
      console.log('this is end ' + item);
  }

  var process = function (item) {
        console.log(item); //this show undefined
        dosomething1(item);
        dosomething2(item);
  }

  var temp = ["a", "b", "c", "d"];
  chunk(temp, process);​

The problem is begin in the process function, the item log undefined, the item could only show correctly in chunk.

So how can I solve this problem?I think it related to the process.call method?Is it related to the context parameter?

You can see the demo here

Upvotes: -1

Views: 594

Answers (3)

just.another.programmer
just.another.programmer

Reputation: 8785

The call method of a function calls the function with a specified this. The first parameter you pass the function (in this case item in your call to process.call(item, context)) will be accessible by the this keyword inside your function.

So, make this change to reference properly:

var process = function () {
    console.log(this);
    dosomething1(this);
    dosomething2(this);
}

Upvotes: 0

Someth Victory
Someth Victory

Reputation: 4549

Yes, you're right. .call method is the concept of inheritance in javascript, and the first parameter in .call method is used for passing current object to its super class, and second parameter which is used as normal parameter. Try this,

var chunk = function (array, process, context) {
    setTimeout(function(){  
        var item = array.shift();  
        console.log('item', item);//this could show correctly
        process.call(this, item);// the first parameter is the current object
        if (array.length > 0){  
            setTimeout(arguments.callee, 100);  
        }  
    }, 100); 
}

Upvotes: -1

Musa
Musa

Reputation: 97672

You pass the context as the first parameter to call, process.call(context, item);. Though you never pass an argument for context to chunk which isn't an issue since you never use this.

http://jsfiddle.net/NrBmD/2/

Upvotes: 0

Related Questions