views:

78

answers:

1

Say I have an object called FieldEdit. I define the function constructor for this object, instantiate it via. var obj = new FieldEdit(), and define its methods by FieldEdit.prototype.<method name> = function() { ... }.

Under what situations would calling this object's methods within the objects' other methods (via. this.<method name>();) fail?

Note that I want to avoid posting a code sample for this if I can since I think this is simply a problem with my understanding of Javascript more than anything, really. I'm pretty sure my code is sound, to the best of my knowledge (and it's my knowledge that's the question here, besides).

+2  A: 

The most likely scenario where this would reference an object other than FieldEdit during execution of FieldEdit methods is within a nested scope like a closure, an event handler, or any function or method called explicitly with .call(someOtherScope) or .apply(someOtherScope, args).

You can work around that, of course, by maintaining a variable reference to the FieldEdit instance and using FieldEditInstance.<method>() instead.

PrototypeJS allows you to wrap functions with Function.bind for this purpose, but it's easily accomplished otherwise, either with:

var FieldEditInstance = this;
obj.methodThatUsesACallback(function() {
    // use that instead of this
});

OR

var FieldEditInstance = this;
var callback = function() {
    // ...
};
// This is more or less what PrototypeJS' Function.bind produces
var boundCallback = function() {
    return callback.apply(FieldEditInstance, arguments);
};
obj.methodThatUsesACallback(boundCallback);
eyelidlessness
Ah. Indeed it is happening in a callback function for a custom event handler I built. What a pain.
Daddy Warbox