创建所有原型函数都可访问的局部变量

shi*_*doo 3 javascript prototype

我正在尝试使用原型向对象添加函数,我以为我理解了整个概念,所以这就是我所做的:

function ImgContainer() {
    var current_image = 1;
}

ImgContainer.prototype = {
    init: function() {
        //initialize
    },
    scrollLeft: function(){
        //scroll left
    }
}

var imgContainer = new ImgContainer();
Run Code Online (Sandbox Code Playgroud)

我假设我可以在init和scrollLeft中访问current_image,但是我得到了Uncaught ReferenceError:current_image没有定义.

我应该怎么做一个可以在init和scrollLeft函数中访问的变量?

Esa*_*ija 5

您可以将其添加为实例化对象的属性:

function ImgContainer() {
    this.current_image = 1;
}
Run Code Online (Sandbox Code Playgroud)

然后在函数中访问属性:

ImgContainer.prototype = {
    init: function() {
        alert(this.current_image);
    },
    scrollLeft: function(){
        //scroll left
    }
}
Run Code Online (Sandbox Code Playgroud)

您仍然可以在方法中使用短期变量来临时存储内容以完成该方法的工作.但是您将对象的状态存储在其属性中.