我来自 C++,发现“this”仅表示执行上下文。是否有保证获得自我实例的方法?
我问这个是因为我总是尝试在javascript中通过“this”来获取实例,但是我必须自己做各种方式来保证它,例如如下所述的方式:
MyClass.prototype.OnSomethingHappened = function () {
// I want to get the reference to the instance of this class.
}
但是这种函数通常被称为:
var bar = new MyClass();
foo.onclick = bar.OnSomethingHappened;
当 onclick 发生时, OnSomethingHappened 被调用,但“this”并不表示 bar 的实例。
有一些解决方案,例如:
var bar = new MyClass();
foo.onclick = function () {
bar.OnSomethingHappened();
}
是的,它在这里完美运行。但请考虑:
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.
}