简体   繁体   中英

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.

What should I do to have a variable that's accessible in both init and scrollLeft function?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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