0

Is it possible to use created objects in another scope?

var iZ = 0;
var pcs = {};
function Pc(_name, _os) //Constructor 
{            
   this.name = _name; // Pc Name
   this.os = _os;    //Pc Os
   this.ausgabe = function()  
   {
   //Do something
   }; iZ++;
}
//Creating a new object 
document.getElementById("pc_create").addEventListener("click", function()
{   
      pcs['pc' + iZ] = new Pc('Pc '+ iZ , os);
      pcs['pc' + iZ].ausgabe();    
});
//Using object in another scope
document.getElementById("run").addEventListener("click", function()
{
      pcs['pc' + iZ].name = "test"; // Doesnt work 
});   

Is there another way to use solve this ?

2
  • seeing iZ being incremented and referenced inside of onclick makes me wonder if that is really the issue. Commented Mar 7, 2016 at 14:02
  • Hey you changed your code entirely! o_0 Commented Mar 7, 2016 at 14:04

2 Answers 2

4

Use,

this.name = _name;

Instead of,

var name = _name;

If you don't assign the name to the current object, then that will become local variable to that constructor. This is applicable for os also.

Also the main error is, whenever you are creating an instance you are updating one variable by increment its count. So if you have created 2 instances, then your 2 objects will be stored like 'pc0' and 'pc1' respectively. But the count iZ will be 2. Now if you access 'pc2' at that time, it will not be fetched, since it was not created. So you could fix it by rewriting your code like below,

 pcs['pc' + (iZ-1)].name = "test";
Sign up to request clarification or add additional context in comments.

2 Comments

Also point out that }); iZ++ is wrong since there is an extra brace there.
@gurvinder372 That was a typo from OP. Just check his question now. Looks like he corrected it by himself.
0

This works now:

document.getElementById("run").addEventListener("click", function()
{
      pcs['pc' + iZ].name = "test"; // Now work 
});   

1 Comment

If you decrement it, then while creating new instances, the already existing instances will be replaced.

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.