我有一个名为 ShippingUI 的 JavaScript 对象:
function ShippingUI(){
...
}
它有几种方法:
ShippingUI.prototype.UpdateItemQTYs = function(ItemJQOBJ, NewQTY)
{
...
}
ShippingUI.prototype.EH_SortableRecieve = function(event, ui)
{
...
}
“EH_SortableRecieve()”函数是一个放置事件处理程序。当它运行时,它需要调用“UpdateItemQTYs()”,这是同一对象中的姊妹函数。我正在尝试使用:
ShippingUI.prototype.EH_SortableRecieve = function(event, ui)
{
this.UpdateItemQTYs('ABCD',123);
}
但不断收到错误:
"this.UpdateItemQTYs is not a function"
我猜测“this”指向其他东西......那么我如何获得“真正的”“this”?
事件绑定(bind)方法:
// Takes a Jquery Object and makes it sortable with our custom options this.MakeSortable = function(JQOBJ) { JQOBJ.sortable({ connectWith: '.connectedSortable', items: '.ItemLineWrapper', dropOnEmpty: true, axis: 'y', receive: this.EH_SortableRecieve }); }
最佳答案
您的示例中缺少一些内容,即 EH_SortableRecieve 的调用方式。但根据你所说的,它应该被使用,因为我认为它的使用是这样的:
htmlelement.onmouseup = shippingObject.EH_SortableRecieve;
在这种情况下,您应该了解 Javascript 在方法中对 this
的绑定(bind)。具体来说,在事件处理程序中,this
绑定(bind)到 window
对象,而不是该方法所属的对象。这是 javascript 的一个普遍特征:方法可以在运行时重新绑定(bind)。换句话说,对象可以窃取其他对象的方法。例如,我可以让我的对象 slebetmans_object
窃取您的方法并使用以下内容重新绑定(bind)其 this
:
shippingObject.EH_SortableRecieve.apply(slebetmans_object,parameters);
有几种策略可以解决这个问题。您可以使用闭包来捕获您的对象:
htmlelement.onmouseup = function(){ shippingObject.EH_SortableRecieve() };
您可以在对象的构造函数中使用闭包来捕获对对象的正确引用:
function ShippingUI () {
var self = this; // since self is resolved at the time the object is created
// it always reference to the "correct" object
this.EH_SortableRecieve = function(event, ui)
{
self.UpdateItemQTYs('ABCD',123);
}
}
可能还有其他方法可以做到这一点,但这是我个人最常用的两种。
关于javascript - JavaScript : Accessing another method of the same object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2270733/