0

Trying to create a "class" in JavaScript that can both have a function at the root of the class and other sub functions:

Validate(word) - returns true or false if the word is validated

Validate.getRule() - returns the rules used to validate the word.

Here is example code:

var Validate = function (word)
{
  this.rule = /^[a-m]$/;

  if (word)
  {
     return this.rule.test(word);
  }
  else
  {
     return {
        getRule   :   function()
           { return this.rule;}
            };
  }

}();

This works the first time if you call it with no arguments, but the second time I get the following error:

TypeError: object is not a function
Jason
  • 13,563
  • 15
  • 74
  • 125

2 Answers2

2

You have scope issues.

var Validate = function (word)
{
  var that = this;

  this.rule = /^[a-m]$/;
  if (word)
  {
     return this.rule.test(word);
  }
  else
  {
     return {
        getRule   :   function()
           { return that.rule;}
            };
  }

}();
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • Beat me to it :) I would add that this is not really a good way to structure code in regards to scalability and maintainability - but that might not be an issue (and I know it wasn't part of the question)... – Joe Dyndale Sep 04 '12 at 21:59
  • Hm... `Validate("asfd")` gives `TypeError: Validate is not a function` – Guffa Sep 04 '12 at 22:01
1

As you are calling the function directly, the word parameter is always undefined, this is the global scope (window), so the code does the same as:

var rule = /^[a-m]$/;
var Validate = {
  getRule: function() { return this.rule; }
};

If you want something to work as both a function and an object, declare the function and then add properties to it (as a function is actually an object):

var Validate = (function(){

  var rule = /^[a-m]$/;

  function validate(word) {
    return rule.test(word);
  }

  validate.getRule = function() { return rule; };

  return validate;

})();
Guffa
  • 687,336
  • 108
  • 737
  • 1,005