Short description: I am using OO Javascript with the function declaration, new keyword, and prototype approach (example below). I need a way to reference the “self” object within each method of the object. “this” seems to only work if I am calling the method directly, otherwise “this” seems to refer to whatever called the method instead.
More details: Here is a simplified version of my object.
function Peer(id) {
this.id = id;
this.pc = new RTCPeerConnection(SERVER);
this.pc.onevent1 = this.onEvent1;
this.pc.onevent2 = this.onEvent2;
}
Peer.prototype.doSomething = function() {
// create offer takes one param, a callback function
this.pc.createOffer(this.myCallback);
};
Peer.prototype.onEvent1 = function(evt) {
// here this refers to the RTCPeerConnection object, so this doesn't work
this.initSomething(evt.data);
};
Peer.prototype.myCallback = function(data) {
// here this refers to the window object, so this doesn't work
this.setSomething = data;
};
Peer.prototype.initSomething = function(data) {
// use data
};
And here is a sample use of it.
var peer = new Peer(1);
peer.doSomething();
// eventually something triggers event1
I tried to simplify the code as much as possible and explain the problem in comments. I created a workaround for the first scenario (calling this.myCallback) by creating a local copy of this and making the callback param an anonymous function that calls the function I need using my local copy of this. But the second scenario is more troublesome (an event firing).
I was curious if there is a different model for Object Oriented programming in which every method always has a proper reference to the parent object, regardless of how the method was invoked? Or if there is a different way to create an object as a property of a custom object and bind its events to the custom object’s method? Sorry if this is confusing language! Note that my question has nothing to do with RTCPeerConnection, that just happened to be the project I’m working on currently.
I found this article: http://www.alistapart.com/articles/getoutbindingsituations but I wasn’t totally sure how to use this information?
Yes, there is: it’s called
Function.bind.Likewise, for
myCallback‘sthisto always reference thePeerinstance: