Search code examples
phpjavascriptpersistencescopecode-reuse

How to properly work _around_ Javascript persistence?


There is basic persistence of Javascript vars/etc. You call a function/method, and the next time you call that same function/method, it is holding the data from the last time.

You can delete the vars when you are done with them, but that removes the advantage of using the code again for that instance.

So what is the proper way to write code which can be reused, on different elements, inside the same page.

Therefore, I need the ability to write code so that I can point it at several different elements, and then interact with that code segregated for each element.

So in PHP (as an example) I would do:

$element1 = new MyClass();
$element2 = new MyClass();
$element3 = new MyClass();

in that case it's the same code running in three segregated scopes. How can I do this properly with JS. Even using jQuery's extend() gives me problems.

Thanks.


Solution

  • To create an instance in JavaScript you need to write a constructor function, and call that using new. For instance:

    function MyClass( somevalue ) {
       this.somevalue = somevalue;
       this.somefunction = function() {
         alert(somevalue);
       }
    }
    
    var instance1 = new MyClass(1);
    var instance2 = new MyClass(2);
    var instance3 = new MyClass(3);