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
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: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):
You have scope issues.