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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With