簡體   English   中英

OO JavaScript:訪問同一對象的另一種方法?

[英]OO JavaScript: Accessing another method of the same object?

我有一個名為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”?

事件綁定方法:

// 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的方法。 具體來說,在事件處理程序中, this方法綁定到window對象,而不是方法所屬的對象。 這是javascript的一般功能:方法可以在運行時重新綁定。 換句話說,對象可以竊取其他對象的方法。 例如,我可以有我的對象slebetmans_object竊取你的方法,並重新綁定了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);
    }
}

可能還有其他方法可以執行此操作,但是這是我個人最常用的兩種方法。

問題在於,當您將該函數注冊為事件處理程序時,該函數與對象的關系將會丟失。

您如何注冊事件處理程序? 如果是jQuery,則可以使用新的“代理” API:

$('#someButton').click($.proxy(myShippingUI, 'EH_SortableReceive'));

這將確保對象(我使用“ myShippingUI”作為類的示例實例)充當了“ this”指針。 還有其他方法可以做到這一點,但這很簡單。

“ $ .proxy”是1.4中的新增功能。

function ShippingUI(){
   ...
}

ShippingUI.prototype = {
UpdateItemQTYs : function(ItemJQOBJ, NewQTY)
{
   ...
},
that = this,
EH_SortableRecieve = function(event, ui)
{

that.UpdateItemQTYs('ABCD',123);
    ...
}
};

上面的方法也應該起作用...您所需要的只是對此中當前使用的ShippingUI對象的引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM