0

This might seem like a noob question but I'm not sure what to do. I have function with 2 variables.

function someInfo(myVar1,myVar2)
{
    this.lmyVar1=myVar1;
    this.myVar2=myVar2;
}

myInstance=new someInfo("string1","string2");

function drawVariables(){
    document.write(myInstance.myVar1);
    document.write(myInstance.myVar2);
}

I want to use the same drawVariable() for multiple instances. I just can't figure out how the exact syntax for that. How can I make drawVariable() use a different instance of someInfo without repeating anything? Is there a simple example or tutorial I can follow?

0

3 Answers 3

4

Add an argument to the definition of function drawVariables. In the code below, this argument is called info. Now you can use info as your object inside the drawVariables function, and while calling drawVariables function, you can pass whatever instance you want to pass it. drawVariables function would now work with whatever instance you pass it while calling.

function someInfo(myVar1,myVar2)
{
    this.myVar1=myVar1;
    this.myVar2=myVar2;
}

// Create two separate instances
myInstance=new someInfo("string1", "string1");
myInstance2 = new someInfo("string2", "string2");

// info is the argument that represents the instance passed to this function
function drawVariables(info){
    alert(info.myVar1 + ", " + info.myVar2);
}

// Call the function twice with different instances
drawVariables(myInstance);
drawVariables(myInstance2);

See http://jsfiddle.net/WLHuL/ for a demo.

Sign up to request clarification or add additional context in comments.

Comments

1
function drawVariables(instance){
    document.write(instance.myVar1);
    document.write(instance.myVar2);
}

Comments

0

Would it make sense for you to do it this way?

function someInfo(myVar1, myVar2)
{
    this.lmyVar1 = myVar1;
    this.myVar2 = myVar2;
    this.drawVariables = function ()
    {
        document.write(this.lmyVar1);
        document.write(this.myVar2);
    }
}


function Test()
{
    var obj1 = new someInfo("aaa", "bbb");
    var obj2 = new someInfo("xxx", "zzz");

    obj1.drawVariables();
    obj2.drawVariables();
}

1 Comment

I was looking for something a little more generic, but this is great. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.