[英]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.