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

create local variables accessible to all the prototype functions

本文关键字:访问 局部变量 函数 原型 创建      更新时间:2023-09-26

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

function ImgContainer() {
    var current_image = 1;
}
ImgContainer.prototype = {
    init: function() {
        //initialize
    },
    scrollLeft: function(){
        //scroll left
    }
}
var imgContainer = new ImgContainer();

我假设我可以在 init 和 scrollLeft 中访问current_image,但我得到了未捕获的引用错误: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();