Skip to content Skip to sidebar Skip to footer

How Can I Use An Object As A Function And An Object?

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 valid

Solution 1:

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;}
            };
  }

}();

Solution 2:

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;

})();

Post a Comment for "How Can I Use An Object As A Function And An Object?"