Reputation: 5026
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.
Upvotes: 3
Views: 110
Reputation: 318518
$.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()
.
Upvotes: 4
Reputation: 1710
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();
Upvotes: 1
Reputation: 198324
When you write array[0].testF()
, this means:
array
"0"
"testF"
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.
Upvotes: 1
Reputation: 185933
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 );
.
Upvotes: 2