Regarding the object below I am getting a ” ‘this’ is undefined error”. This only occurs in the next() function block…as commented below, if it is placed in the Effects function block there is no error.
This is only test code…my goal is to pass the element in through the constructor. This test code has it passed in from both the constructor and the function because I’m testing it. Once it passes I will take out the function argument from fade().
Also the Object Usage, happens to be in another object, that is why you see “this” there as well.
Object Usage:
var EffectsObject = new Effects( this.element );
EffectsObject.fade( this.element, 'down', 4000);
Object Definition:
var Effects = function( element )
{
this.element2 = element;
};
Effects.prototype.fade = function( element1, direction, max_time )
{
Effects.elapsed = 0;
this.element2 = foo; // works here but not if I put it in next();
function next()
{
Effects.elapsed += 10;
if ( direction === 'up' )
{
element2.style.opacity = Effects.elapsed / max_time; // fails here
}
else if ( direction === 'down' )
{
this.element2.style.opacity = ( max_time - Effects.elapsed ) / max_time;
}
if ( Effects.elapsed <= max_time )
{
setTimeout( next, 10 );
}
}
next();
return true;
};
You need to create a variable that is in the lexical scope of the the
nextfunction.var that = this;above
next, and usethatinnext.The problem is when you define a method on a prototype, and then execute that method on the instance of an object, the context of the method (the scope) is set when you call the method. When that happens
thispoints at the instance on which the method was invoked.When you defined
next, note it’s not part of any prototype. It’s just a function. When you execute it, the context of the execution (i.e.this) is not the instance of the object.When you define
that, and then use it in the function,thatis in the lexical scope of thenextfunction. When you invokenext, a closure is created, locking the value ofthatinto the execution scope ofnext.