简体   繁体   English

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

[英]create local variables accessible to all the prototype functions

I'm trying to use prototype to add functions to an object, I thought I understand the whole concept, so here's what I did: 我正在尝试使用原型向对象添加函数,我以为我理解了整个概念,所以这就是我所做的:

function ImgContainer() {
    var current_image = 1;
}

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

var imgContainer = new ImgContainer();

I assume I can access current_image in both init and scrollLeft, but I'm getting Uncaught ReferenceError: current_image is not defined. 我假设我可以在init和scrollLeft中访问current_image,但是我得到了Uncaught ReferenceError:current_image没有定义。

What should I do to have a variable that's accessible in both init and scrollLeft function? 我应该怎么做一个可以在init和scrollLeft函数中访问的变量?

You would add it as a property of the instantiated objects: 您可以将其添加为实例化对象的属性:

function ImgContainer() {
    this.current_image = 1;
}

Then access the property in the functions: 然后在函数中访问属性:

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

You can still use short lived variables inside methods to store stuff temporarily to get that method's job done. 您仍然可以在方法中使用短期变量来临时存储内容以完成该方法的工作。 But you store the object's state in its properties. 但是您将对象的状态存储在其属性中。

You can't reach private members of an object via prototype methods outside the object because they are out of the scope. 您无法通过对象外部的原型方法访问对象的私有成员,因为它们超出了范围。 You should do it like this: 你应该这样做:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM