簡體   English   中英

父作用域中的訪問變量

[英]Access variable in parent scope

我正在嘗試從selectable對象中的函數內部訪問selectItems數組,但是不確定是否有一種方法可以將_Multiselect對象作為參數傳遞回函數中。 還有其他方法嗎?

function _MultiSelect() {
}
_MultiSelect.prototype = {

    selectedItems: [],

    selectable: {

        myFunc: function(){
            //how can I access selectedItems from here
        }
    }
}

一種選擇是使函數成為selectable函數,該函數返回包含myFunc和其他內容的對象。 這樣,您就可以捕獲閉包中的_MultiSelect上下文,並將其用於您公開的方法中。

_MultiSelect.prototype = {

    selectedItems: [],

    selectable: function() {
       var context = this;
       return {
          myFunc: function(){
            console.log(context.selectedItems);
            //how can I access selectedItems from here
          }
       }
    }
}

用例:

(new _MultiSelect).selectable().myFunc();

您可以在下面的代碼中存儲此上下文

    _MultiSelect.prototype = {

    selectedItems: [],

    selectable: function() {
        // store the context of this in that
       var that = this;
       return {
          myFunc: function(){
            // is accessible
            console.log(that.selectedItems);
          }
       }
    }
}

暫無
暫無

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

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