簡體   English   中英

如何在不使用JavaScript或self的情況下在函數內部訪問此函數?

[英]how can I access this inside a function without using that or self in javascript?

我試圖用JavaScript編寫一些OOP,但我偶然發現了一個問題,我確信我稍后會在我的代碼中遇到這個問題,希望現在就解決。

例如,使用以下代碼:

var FeedClass = function(){

    this.init = function(){
        this.loadItems();
    },
    this.loadItems = function(){
        var that = this; // heres my problem
        function inner(){
            that.startLoading();
        }
        inner();
    },
    this.startLoading = function(){
        alert("started Loading");
    }

    this.init();
};

var feed = new FeedClass();

問題是我將要使用很多內部函數來調用"this" ,如果我在每個范圍內一直寫var that = this ,我的代碼將很混亂。 有沒有我可以使用的其他模式或解決方法?

您可以使用call方法來設置函數的上下文:

this.loadItems = function(){
    function inner(){
        this.startLoading();
    }
    inner.call(this);
},

apply方法的工作原理類似,不同之處在於您如何在調用中指定參數。

您還可以使用bind方法來設置函數的上下文。 這樣,您就可以將上下文綁定到函數,並將函數引用傳遞給以后調用:

this.loadItems = function(){
    function inner(){
        this.startLoading();
    }
    var i = inner.bind(this);
    i();
},

注意:IE 8或更早版本不支持bind方法。

暫無
暫無

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

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