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

陌路散爱 提交于 2019-12-12 02:19:41

问题


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

}();


来源:https://stackoverflow.com/questions/12271791/how-can-i-use-an-object-as-a-function-and-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!