Search code examples
javascriptoopencapsulation

Encapsulationn in Javascript


Here is the nature of my problem:

function theObject(){
    this.theMethod = function(theParameter){
    //code that uses theParameter
    }

    this.anotherMethod = function(){
        for(var x = 0; x < 10; x++){
            document.writeln("<img src = 'loc.jpg' onclick ='" + this + ".theMethod(" + x  + ")'>");
        }
    }

I think it's pretty straightforward to see what I'm trying to do here...but it doesn't work. The HTML doesn't know what any of my "classes" are. I've tried many variations, including using getElementById().addEventListener() but with that route the for loop variable changes out from under me.

How do you do this? NO jquery please AND "theMethod" must remain encapsulated.

Thanks


Solution

  • This should work well for you. Here's a working demo

    function theObject(){
    
      this.theMethod = function(theParameter){
        //code that uses theParameter
      };
    
      this.anotherMethod = function(){
        for(var x = 0; x < 10; x++){
          var img = document.createElement("img");
          img.src = "loc.jpg";
          img.onclick = this.theMethod.bind(this, x);
          document.appendChild(img);
        }
      }
    }
    

    Using Function.prototype.bind requires ECMAScript 5 or higher. If you need to support old dinosaur browsers, please look into es5-shim

    If you still can't support .bind, @6502's answer is your next best bet.