提供功能名称时,检查功能是否存在于同一范围内

时间:2015-04-01 11:54:51

标签: javascript function

我有format原型方法(简化),我想做的是检查char是字母(不区分大小写),,如果它是也是在相同范围中声明的函数。如果是,我想调用该函数。因此,如果我传入x,它应该执行警报。

我将使用此方法按给定的格式字符串格式化日期。例如。 format('H:i:s')它会检查H,i和s是否为函数并调用它们。

如何实现?

我根据这个答案尝试了一些事情:https://stackoverflow.com/a/359910/1115367

这是我的代码:

function Time() {
    //initialization
}

Time.prototype = {
    format: function (char) {
        if (char.test(/[a-z]/i) && typeof window[char] === 'function') { //undefined
           window[char]();
        }

        function x() {
            alert('works');
        }
    }
};

如果我传入一个值,则返回:Uncaught TypeError:undefined不是函数

3 个答案:

答案 0 :(得分:0)

test()不是字符串的函数,它是RegExp的函数。请参阅test此处的文档:RegExp.prototype.test()

因此,首先创建一个RegExp对象,然后使用它来调用test,并传入字符串char

在更多地查看您的代码之后,我认为您需要将您的格式功能转变为'类' (JavaScript并不真正有类,但您可以从函数创建对象。)

function Formatter() {
    this.format = function(char) {
        var regex = /[a-z]/i;

        if (regex.test(char) && typeof this[char] === 'function') {
           this[char]();
        }
    };

    this.x = function() {
        alert('works');
    }
}

var formatter = new Formatter();

formatter.format('x');

这是工作jsfiddle

如您所见,您创建了一个格式化程序对象,其中包含format函数和x函数,范围为this

答案 1 :(得分:0)

没有办法按名称检索局部变量(或函数)(据我所知)。

声明的命名函数被分配给同名的变量:function thing(){}var thing = function(){}

全局变量会自动附加到window,因此您可以使用window对象按名称检索它们。

然而,(幸运的是)并非所有其他变量的情况。

例如

var global1 = 'thing'; // root level (no wrapping function) -> global

(function(){
    global2 = 'global';     // no 'var' keyword -> global variable (bad practice and not accepted in strict mode)
    var local = 'whatever'; // local variable

    function check(name){
        if(window[name]) console.log('found: '+ name);
        else console.log('nope: '+name);
    }

    check('foo');
    check('global1');
    check('global2');
    check('local');
}());

将输出:

[Log] nope: foo
[Log] found: global1
[Log] found: global2
[Log] nope: local

但是,您可以将方法附加到对象上。

修改

如果是一个选项,你也可以直接将函数作为参数传递(而不是包含其名称的字符串)。

function a(){}

function toCall(f){
   // do stuff with f
}

toCall(a);

答案 2 :(得分:0)

您可以使用立即调用的函数表达式(IIFE)来创建范围:

var Time = (function() {
  var handlers = {
    x: function () {
      console.log('x invoked');
    }
  };

  function Time() {
    // fun stuff
  }

  Time.prototype = {
    format: function(char) {
      handlers[char](); // if char === 'x'
    }
  };

  return Time;
}());