You need to learn about binding. By default, "this" points to the object
that the function is a member of:
function foo(){ alert(this) }; //alerts window, because foo is a member of
window: window.foo
var foo = {
bar: function(){ alert(this) } //alerts foo, because bar is a member of
foo: foo.bar
};
When we use functions as arguments we often need to preserve the pointer to
our reference object, as in your example. We have three ways to do this:
1) Function.bind
loadData:function(data){
data.each(function(item,index){
alert(index + ': ' + item);
this.milk_Grid.push(item);
}*.bind(this)*);
alert('Data Loaded!');
}
2) some things take the "this" as an argument; array.each/map/filter/etc
allow this:
loadData:function(data){
data.each(function(item,index){
alert(index + ': ' + item);
this.milk_Grid.push(item);
}*, this*);
alert('Data Loaded!');
}
3) create a pointer to "this" and reference it
loadData:function(data){
*var self = this;*
data.each(function(item,index){
alert(index + ': ' + item);
*self*.milk_Grid.push(item);
});
alert('Data Loaded!');
}
In general, if you can pass "this" as an argument (option 2) you should;
it's faster. MooTools generally prefers option 1 over option 3.
On Wed, May 12, 2010 at 10:37 AM, Paul Saukas <[email protected]> wrote:
> OK,
>
> I am having a bit of a problem as I try to teach myself classes. I have
> the following code :
>
> Mooshell: http://mootools.net/shell/T8xDe/3/
>
> Class Function:
>
> loadData:function(data){
> data.each(function(item,index){
> alert(index + ': ' + item);
> this.milk_Grid.push(item);
> });
> alert('Data Loaded!');
> }
>
> Call To class Function :
>
> var data = [
> ['border', '#FF0000'],
> ['color' , '#0000FF'],
> ['font-weight', 'bold']
> ];
>
> myTable.loadData(data);
>
>
> What vexes me is i get an error saying "this.milk_Grid" is undefined. This
> only happens if i call the push on it from within the each loop so I am not
> sure if it is a matter of the each overriding the "this", or if i am just
> doing something horribly wrong.
>