我来自 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.
}
最佳答案
不,“类”的概念在 JavaScript 中并不像在 C++ 中那样存在。函数和任何特定对象之间没有内在关系。函数只是值。
(当对象具有引用函数的属性时,除了“偶然”关系之外没有其他关系。)
但是,可以通过将一个函数包装在另一个使用 .call()
或 .apply()< 的函数中来强制
调用目标函数。您可以在较新的浏览器中使用 this
的特定值.bind()
来做到这一点,或者简单地使用匿名(或非匿名)包装器。
编辑 — 了解this
的重要之处在于它的值完全由调用函数的方式决定,在每一点的调用。因此,如果您有一个对象:
var myObj = new Something();
并且您想使用 myObj.handler
作为事件处理程序(常见情况),以便事件处理程序中的 this
引用该对象,您只需要一个包装器:
$('whatever').click( function(ev) { myObj.handler(ev); } );
在该示例中,“myObj”不必是全局变量:
function justAnExample() {
var myObj = new Something();
$('whatever').click( function(ev) { myObj.handler(ev); } );
}
您可以清楚地看到“myObj”是“justAnExample”函数内的局部变量。因为 JavaScript 有真正的闭包,“justAnExample”的调用上下文在调用后被保留下来,供作为事件处理程序传递给 jQuery 的匿名包装函数使用。
关于javascript - 保证获取类实例的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14297850/