views:

673

answers:

4

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.

+6  A: 

Use the var keyword when defining local variables (otherwise they'll default to globals).

function foo() {
    var i;
    // code code code code
}
grawity
I have still experienced many issues with this. However, so the use of _var_ does not just effect namespace in the block structure, it impacts persistence scope as well?
Spot
There is no "persistence" - if you don't use 'var', you're simply declaring the variables as global, so they don't get unset after the function returns. (At least I think so.)
grawity
So how can you use difference instances of the same var at the same time (same page)? Which is what I'm looking for. I know it's doable, I am just not sure what is the best way to achieve it.
Spot
You just have to be sensible about your scope. It sounds like you are experiencing race conditions of some sort - if "Use var" doesn't answer the question, then you might want to be more specific about the code that is causing you problems.
David Dorward
+1  A: 

You can namespace your JavaScript to make it a lot like what you're after. See below for an example. It does sound like your problem is related to using global variables where you want to use local variables though - i.e. you declare var myvariable; outside of your function, but only want to use it and forget it within your function. In that case, declare the variable inside your function to make it local.

var MyNameSpace = function() {
return {
 sayhello : function() {
  alert("hello");
 },
 saygoodbye : function() {
  alert("see ya");
 }
};

}();

Sohnee
This is actually an associative array of functions - and the outer function() {}, and the return, is unneeded.
grawity
I don't want to 'use it and forget it' though. I want to be able to use it, and reference it _specifically_, while also referencing it specifically for other instances. I am looking for proper _instancing_. If that makes sense.
Spot
You can actually declare a "var" inside of that "namespace", which would mean it would exist within your instance of that name space, but wouldn't interfere with other variables outside of it. Just declare "var private_var;" by adding it to a new line before the word return (this is why you actually do want the outer function and the return too!)
Sohnee
+3  A: 

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);
Mario Menger
Ok, actually I have read a bit about using a constructor for this, but could never find anything strait forward about what constitutes a constructor in JS. In PHP you just use function __construct(), but in most cases when trying to instantiate a class in JS it throws an error, claiming that there is not a constructor. So what makes a constructor a constructor (in JS)? Thanks.
Spot
A constructor function in JavaScript is like a class definition and constructor function as seen in other languages but rolled into one.
Mario Menger
Ok, that gives me a little more info. I'll google for more. Thanks!
Spot
A: 

It sounds like what you're looking for is the ability to have instances of a class and have private data that's associated with each instance.

You can do this using the following technique:

function Foo()
{
    // Member variable only visible inside Foo()

    var myPrivateVar;       

    // Function only visible inside Foo()

    var myPrivateFunction = function() 
                            { 
                                alert("I'm private!");
                            }

    // Member variable visible to all

    this.myPublicVar = "Hi, I'm public!";

    // Function visible to all

    this.myPublicFunction = function()   
                            {
                                myPrivateVar = "I can set this here!";
                            }
}

You can create and use one of these using the following syntax:

var myFoo = new Foo();

myFoo.myPublicVar = "I can set this!";
myFoo.myPublicFunction();
17 of 26