0

So here is the thing. Am creating an instance of an object var newInstance = new MyObject() on click of a button, but i want to make sure that when the button is clicked, it checks to see if that particular instance newInstance of that object MyObject has been created already, which if it has been created, prevent it from creating that instance again. I hope its clear enough.

This is what i have tried so far:

button.addEventListner("click", function(){
   if(newInstance instanceof MyObject){ // also tried newInstance instanceof Object
       return false; // this didn't work, i tried using preventDefault(); and to no avail
       // at this point i don't want the instance to be created anymore
   }
   else{
       var newInstance = new MyObject(); // create the instance
   }
});
  • Possible duplicate of [JavaScript check if variable exists (is defined/initialized)](https://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized) – Renaldo Balaj Nov 29 '19 at 12:32
  • 1
    make `newInstance` global. – briosheje Nov 29 '19 at 12:33
  • Keep newInstance as this.newInstance and use this same condition if `this.newInstance!=null` while creating obj. – Tejas Nov 29 '19 at 12:33
  • Please could you guys back up your answers with the possible code. Thank You – Redemption Okoro Nov 29 '19 at 12:34
  • You're declaring `var newInstance` inside the listener function so it won't be accessible outside (and shadow the possibly already existing variable). Your code is more or less fine if you fix that: https://jsfiddle.net/khrismuc/wo8vmxy0/ Or use the Singleton pattern: https://jsfiddle.net/khrismuc/wo8vmxy0/3/ – Chris G Nov 29 '19 at 12:37
  • i'll try it out and see...feedbacks coming soon – Redemption Okoro Nov 29 '19 at 12:45

1 Answers1

0

It all depends on the scope of the object. In your code the newInstance object is only available to that invocation of the function. Next time it runs it doesn't know anything about the last newInstance.

If instance you make the scope of newInstance external to your function, then it works:

var newInstance = null;

button.addEventListner("click", function(){
   if(newInstance){ // also tried newInstance instanceof Object
       return false; // this didn't work, i tried using preventDefault(); and to no avail
       // at this point i don't want the instance to be created anymore
   }
   else{
       newInstance = new MyObject(); // create the instance
   }
});

If you dont want newInstance on the global scope then you could use this.newInstance = ... (as suggested by @Tejas) wrap the above in a closure:

(function(){
    //Code from above
})();
Chris Charles
  • 4,266
  • 15
  • 29