[英]create local variables accessible to all the prototype functions
我正在嘗試使用原型向對象添加函數,我以為我理解了整個概念,所以這就是我所做的:
function ImgContainer() {
var current_image = 1;
}
ImgContainer.prototype = {
init: function() {
//initialize
},
scrollLeft: function(){
//scroll left
}
}
var imgContainer = new ImgContainer();
我假設我可以在init和scrollLeft中訪問current_image,但是我得到了Uncaught ReferenceError:current_image沒有定義。
我應該怎么做一個可以在init和scrollLeft函數中訪問的變量?
您可以將其添加為實例化對象的屬性:
function ImgContainer() {
this.current_image = 1;
}
然后在函數中訪問屬性:
ImgContainer.prototype = {
init: function() {
alert(this.current_image);
},
scrollLeft: function(){
//scroll left
}
}
您仍然可以在方法中使用短期變量來臨時存儲內容以完成該方法的工作。 但是您將對象的狀態存儲在其屬性中。
您無法通過對象外部的原型方法訪問對象的私有成員,因為它們超出了范圍。 你應該這樣做:
function ImgContainer() {
var current_image = 1;
this.init = function() {
current_image = 'something_blahblah';
}
}
var imgContainer = new ImgContainer();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.