![](/img/trans.png)
[英]How can I access a property defined in a constructor of a class inside a method of the same class in Javascript without using this keyword?
[英]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.