3

Excuse the beginner question, but I'm having difficulty wrapping my head around this. Using jquery I can do something like this:

$.each(array, testF); 

function testF(){
    console.log(this.name);  
}

Using $.each I can pass the array to the the function testF, and access the object contained within each row of the array. But when I try to do something like:

array[0].testF()

I get an error stating that the Object has no method 'testF'. I'm wondering if someone can explain what's happening here... why the jQuery one works, but the second doesn't. Again, please excuse the beginner question.

4 Answers 4

4
  • $.each(array, testF) calls testF(i, elem) for each element in the array with this bound to elem.
  • array[0].testF() tries to call a method testF() that exists on array[0]

The equivalent of what $.each() does is testF.call(array[0], 0, array[0]) or since you do not use the arguments you can simpl do testF.call(array[0])

See MDN for the documentation of .call().

Sign up to request clarification or add additional context in comments.

2 Comments

How does jQuery bond this to testF?
It uses .call(); a method every function in JavaScript has. Here's the statement copied from the jQuery source: callback.call( object[ i ], i, object[ i++ ] )
2

Do it like so:

testF.call( array[0] );

The call function method enables you to set the context (the this value) of the function invocation. So, whenever you want to invoke a function with a custom context, instead of fn();, do fn.call( context );.

Comments

1

When you write array[0].testF(), this means:

  • Look up the variable array
  • Take the element under the index "0"
  • Within that, take the element under the index "testF"
  • and execute it as a function (also assigning the special variable this to array[0])

However, in most circumstances, array[0] will not have an attribute testF defined. If you were to do this beforehand:

array[0].testF = testF;

then it would work.

3 Comments

I'd replace #3 with "Lookup the property "testF" of that element".
@ThiefMaster: Fair enough; even though arrays in JavaScripts are just special objects, with numeric property names so I meant to show the equivalence.
I appreciate the step-by-step explanation. Thanks.
1

this is because the object array[0] has no function testF, You will need to declare that first. like so:

array[0].testF = function testF()
{
    console.log(this.name);
}

array[0].testF();

Comments

Your Answer

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.