Reputation: 5880
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);
}
Upvotes: 0
Views: 106
Reputation: 2322
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.
Upvotes: 2
Reputation: 13956
var obj;
function loaded(){
obj = new ObjectExample();
}
function updateObject(event){
console.log(obj);
}
Upvotes: 1