Thomas 'PointedEars' Lahn wrote:
Richard Cornford wrote:
>Thomas 'PointedEars' Lahn wrote:
>>Thomas 'PointedEars' Lahn wrote:
window.setInter val(this.m_two, 500);
Correction, use this instead to retain the method-object
relationshi p:
window.setInter val(function callTwo() { this.m_two(); }, 500);
That is not going to help because when setInterval executes the
function expression (or the object resulting from the evaluation
of the function expression, to be precise) the - this - reference
inside that function will be to the global object and so -
this.m_two - will have the same meaning as when it was in the
string in the earlier examples.
True, a closure is required:
A closure is (or probably is) required, but only one.
this.m_one = function()
{
var me = this;
window.setInter val(function() { me.m_two(); }, 500);
};
this.m_two = function()
{
window.alert(th is.m_one);
};
As you have it every call to - m_one - will create a new function object
and a new closure. But if the closure was formed in the constructor (or
by other means (e.g. in an external function), but once only) with the -
m_two - method then the result would be more efficient.
function AnObject(){
var self = this;
this.m_two = function(){
// have this function refer to its object instance through the
// scope chain instead of through the - this - keyword and
// you only need one instance of this function
alert(self.m_on e);
};
}
// and - m_one - does not need to created in the constructor
AnObject.protot oype.m_one = function(){
setInterval(thi s.m_two, 500);
};
And if the idea of creating the closure at the time of instantiation the
object did not appeal the 'Russian Doll' pattern (or similar) could be
applied to create it once, but at the first call to - m_one -.
function AnObject(){
}
AnObject.protot oype.m_two = function(){
alert(this.m_on e);
};
AnObject.protot oype.m_one = function(){
var self = this;
function atIntervals(){
self.m_two();
}
(this.m_one = function(){
// This is the function that calls to - obj.m() - once use
directly
// following its indirect use in the first call.
setInterval(atI ntervals, 500);
})();
};
Prototype.js was written by ...
One of my gripes about Prototype.js is the way in which it encourages
(even forces) horrendously inefficient use of functions, and especially
functions that are 'bound' to objects. You will often see Prototype.js
code where in real javascript you cold define/use a single instance of a
function and re-use it to your hart's content being implemented so that
a new function object is created on each and every use, or worse, a new
function created and then another with its own closure as the first is
'bound' to some object, but the same object on each occasion.
Richard.