I come from C++, found out “this” only means execution context. Is there a guaranteed way to get self instance?
I ask this because I always try to get instance by “this” in javascript, but I have to do various ways to guarantee it by myself, such as ways described as follow:
MyClass.prototype.OnSomethingHappened = function () {
// I want to get the reference to the instance of this class.
}
But this kind of function is often called like:
var bar = new MyClass();
foo.onclick = bar.OnSomethingHappened;
When onclick happend, OnSomethingHappened get called, but “this” does not mean the instance of bar.
There are some solution like:
var bar = new MyClass();
foo.onclick = function () {
bar.OnSomethingHappened();
}
Yes, it works perfectly here.
But consider:
var bar = new MyClass();
MyClass.prototype.OnSomethingHappened = function () {
// I want to get the reference to the instance of this class.
}
MyClass.prototype.IWantToBindSomething = function () {
// sorry for using jquery in a pure javascript question
$("div#someclass").bind("click", function () {
bar.OnSomethingHappened();
}); // I think this is a very very bad practice because it uses a global variable in a class, but I can't think of other workaround, since I have no guaranteed way of getting the instance.
}
No, the concept of a “class” really doesn’t exist in JavaScript the way it does in C++. There’s no intrinsic relationship between a function and any particular object. Functions are just values.
(Well there’s no relationship other than the “casual” relationship when an object has a property that refers to a function.)
However, it’s possible to force a particular value of
thisby wrapping a function in another function that uses.call()or.apply()to invoke the target function. You can do that with.bind()in newer browsers, or simply with an anonymous (or not-anonymous) wrapper.edit — what’s important to understand about
thisis that it’s value is completely determined by the way a function is invoked, at each point of invocation. Thus, if you have an object:and you want to use
myObj.handleras an event handler (common situation) such thatthisin the event handler refers to the object, you simply need a wrapper:In that example, it’s not necessary that “myObj” be a global variable:
In that you can clearly see that “myObj” is a local variable inside the “justAnExample” function. Because JavaScript has real closures, the invocation context of “justAnExample” is preserved after a call, and it’s there for use by the anonymous wrapper function passed as the event handler to jQuery.