-1

I have this class like so : https://jsfiddle.net/0sh7fLtp/

When I create a new object of this class, my local variable can't be seen even when I assign to window in the class:

function Hilitor() {
    var excat;

    this.setMatchType = function(type) {
        if (type == "exact"){ 
            window.excat = true;
        } 
    };

    this.setRegex = function(input) {
        alert(excat);
    };

    this.apply = function(input) {
        this.setRegex();
    };
}

and this is how i call it :

var myHilitor = new Hilitor();
myHilitor.apply();
myHilitor.setMatchType("exact");
GantTheWanderer
  • 1,255
  • 1
  • 11
  • 19
jsem
  • 181
  • 2
  • 12
  • Possible duplicate of [Define global variable in a JavaScript function](http://stackoverflow.com/questions/5786851/define-global-variable-in-a-javascript-function) – Jared Smith Jan 26 '17 at 20:28

2 Answers2

0

Not sure I completely understand your question but you are trying to compare a variable "excat" to string "excat"... See this fiddle to how you can make your var a string and then get desired output..

https://jsfiddle.net/shemdani/0sh7fLtp/5/

var myHilitor = new Hilitor();
myHilitor.setMatchType("excat");
myHilitor.apply();



function Hilitor()
{
  var excat;

  this.setMatchType = function(type)
  {
     if(type == "excat"){window.excat = true;} 

  };

  this.setRegex = function(input)
  {

   alert(window.excat);

  };

  this.apply = function(input)
  {

      this.setRegex();

  };

}
spooky
  • 1,620
  • 1
  • 13
  • 15
  • no i want exact to to be true when create new object of class – jsem Jan 26 '17 at 20:34
  • Just edited the answer... Please check it out again. – spooky Jan 26 '17 at 20:38
  • This is not the ideal answer. Setting a global `window` var is bad. What happens when you want to initialize another `Hilitor` object? They will both be overwriting the `window.exact` var. See my answer instead – Kevin Jantzer Jan 26 '17 at 20:45
0

Two main problems

1) Your var exact inside the function is not a global variable and so not accessible on the window object. (But that's a good thing).

Your code will work if you remove window.exact for just exact

this.setMatchType = function(type)
  {
     if(type == "exact"){excat = true;} 

  };

2) You are also calling apply before you call setMatchType. Switching them like this works:

var myHilitor = new Hilitor();
myHilitor.setMatchType("excat");
myHilitor.apply();

Working example

Kevin Jantzer
  • 9,215
  • 2
  • 28
  • 52