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:
Then access the property in the functions:
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.