Dolton42
Dolton42

Reputation: 35

If Value is true, create a new instance of an object

Create new instance of an object based on an if statement result comparing user input value with a random value. I want it to create a new instance of an object if that is true and do that each time this comparison yields true.

Would object.create() be the way to do this?

 var firstthing = new thing();

 function createnewthing()
 {
    var entry = document.getElementById('theirentry').value;
    if (oneobjectinaclass == "type1")
    var firstvalueinarray = type1[0];
    else if (oneobjectinaclass == "type2")
    var firstvalueinarray = type2[0]; 
    else if (oneobjectinaclass == "type3")
    var firstvalueinanarray = type[0];
    if (variableassignedtowhichevertype[1] == avaluetocompare)
    {
        numCorrect++;
        alert('You\'re right! ' + numCorrect); 

        //the code I'm trying to get to accomplish this goes here
        //var createanotherthingeachtimethisistrue = new Thing();

    }
    else {
        alert('Wrong!');
    }
}

Upvotes: 0

Views: 107

Answers (1)

Patrick
Patrick

Reputation: 17973

Your problem arises from the concept of Scope, which in JavaScript to put it simple is based on functions.

Therefore, in order to solve your problem you can assign a variable outside of the current scope by typing

value = new Thing();

Where value is a previously created variable in some functional context outside of the current function.


To dig deeper, we need to understand scopes in JavaScript. For more details, refer to Scope (computer science) and for more insight into the matter, Everything you wanted to know about JavaScript scope by Todd Motto goes over it in more detail.

To put it short; A scope is "created" whenever we enter a function, and the environment frame of that scope is used whenever we create or access variables. If a variable is not available, the outer context (or environment frame) is used. So to put it in an example.

Example 1

var toy = 'stick';
function changeToy() {
   var toy = 'ball';
}
changeToy();

compared to Example 2

var toy = 'stick';
function changeToy() {
   toy = 'ball';
}
changeToy();

In Example 1 a new variable will be created and assigned because the environment frame is local to the function changeToy. In Example 2 the variable toy is not found in the environment frame for changeToy, so the outer context (the global context in this case) is used; in which the variable is found, and reassigned.

Upvotes: 1

Related Questions