Okay, I’m hating Javascript right now, and I hope someone can help me.
I have code which is set up like the following:
function Obj1() {
var me = this;
this.something = "yay";
this.getThis = function(){
return me;
}
}
Obj1.prototype.method = function() {
return this.something;
};
function Obj2() {
this.something = "nay";
}
Obj2.prototype.method = function() {
return this.something;
};
var o1 = new Obj1();
var o2 = new Obj2();
document.write(o1.method()); // Returns yay
document.write(o1.method.call(o2)); // Returns nay, but I need "yay" here
(JSFiddle @ http://jsfiddle.net/A9u9K/)
My Problem is, that I need to call Obj1.method in the second case, but I am absolutely unable to get a reference to the object 🙁
How can I work around this?
Edit: Sorry, I got my example code pretty wrong 🙁 Updated it. I took most of the code from a previous answer, because it is much nicer and still illustrates my problem.
Updated Answer:
You’ve said you’ve got it sorted now, but as the answer to that isn’t actually shown here on SO, I figured I may as well update to show it.
If it’s
methodyou want to have accessme, even if it’s been called with a differentthisvalue, you have to define it likegetThis, as a closure overme:…or of course, if you don’t need the “something” to be a property on the object, just make it a var within the constructor (a private variable, like
me):Original Answer: (To Revision 1 of the question, which didn’t have
me.)thisis set entirely by how a function is called, not where it’s defined; more about that here and here. But the way you’ve defined yourgetThisfunction, you can use the fact it closes over the constructor call to solve this (no pun) without usingthis:Live example
More about closures and the plumbing that makes the
mething work here.There is a cost involved in this, and just generally in your pattern of defining functions within the constructor function: Each individual object created by
Obj1andObj2gets its own copy of each function. This can have memory implications if there are lots of these objects running around (but unless you have lots, you needn’t worry and you get benefits like themething and other private variables). In constrast, if you use a function assigned to the prototype, all instances will share a single, common copy of the function.In your sample code, only the
getThisfunction really needs to be duplicated for every instance (because you’re relying on the closure), so you can do this to avoid unnecessary function proliferation: