-1

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

asked Aug 8, 2012 at 6:21

3 Answers 3

0

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/

answered Aug 8, 2012 at 6:27
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}
answered Aug 8, 2012 at 6:30

Comments

-1

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); 
}
answered Aug 8, 2012 at 6:28

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.