How can I use an object as a function and an objec

2019-08-29 03:28发布

问题:

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

回答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;

})();


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

}();