Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 246
shibbydoo Avatar asked Feb 03 '26 13:02

shibbydoo


1 Answers

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.

like image 131
Esailija Avatar answered Feb 06 '26 03:02

Esailija