wjhplano
wjhplano

Reputation: 591

passing an object to a function in javascript

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?

Upvotes: 0

Views: 71

Answers (3)

Steve Wellens
Steve Wellens

Reputation: 20640

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();
}

Upvotes: 0

Lone Learner
Lone Learner

Reputation: 20698

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.

Upvotes: 4

Emanuele Paolini
Emanuele Paolini

Reputation: 10172

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

Upvotes: 1

Related Questions