0

If I create an object in an onLoad function, then attempt to reference that object within an onChange function, the object is 'undefined'... how do I reference it?

HTML:

<body onLoad="loaded()">
    <select onChange="updateObject(event)">
        <option value="v1">--v1--</option>        
        <option value="v2">--v2--</option>
    </select>
</body>

JS:

function loaded(){             
    var obj = new ObjectExample();
}
function updateObject(event){
    console.log(obj);
}

2 Answers 2

2

What you are dealing with here is variable scope. The object 'obj' only exists within the 'loaded' function as that is where it is declared. A quick and easy way to solve this problem is to give the variable a larger scope. Eg, a global scope.

var obj;

function loaded(){                  
    obj = new ObjectExample(); 
} 
function updateObject(event){     
    console.log(obj); 
}

The 'obj' variable now exists on the 'window' object (try typing in window.obj in your browser console tool!).

Hope that helped.

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

Comments

1
var obj;

function loaded(){             
    obj = new ObjectExample();
}
function updateObject(event){
    console.log(obj);
}

Comments

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.