JavaScript typeof,alert和apply

时间:2012-09-11 11:30:51

标签: javascript

1)为什么在IE 8中 typeof(window [“alert”])是“对象”而不是功能?
2)如何在“window.alert”上调用apply方法?我的意思是我要做的就是:

function exec(method, param)
{
    //because of typeof(window["alert"]) == "object" the actual if looks like typeof(window[method]) == 'function' || method == 'alert'
    if(typeof(window[method]) == 'function')
    {
        window[method].apply(window, [param]);
    }
}

exec("alert","hello");

3 个答案:

答案 0 :(得分:1)

  1. typeof window ['alert']是一个“功能”......(用FF测试)
  2. 尝试此代码(typeof而不是typeOf())

    function exec(method, param)
    {
        if(typeof window[method] == 'function')
        {
            window[method].apply(window, [param]);
        }
    }
    
    exec("alert","hello");
    

答案 1 :(得分:1)

typeof window["alert"]在9以下的Internet Explorer版本中返回“object”,但在Firefox中它返回“function”。我想这是一个众所周知的问题。下面是一篇提到它的文章:

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/typeof?redirectlocale=en-US&redirectslug=Core_JavaScript_1.5_Reference%2FOperators%2FSpecial_Operators%2Ftypeof_Operator

答案 2 :(得分:0)

  1. typeof(window [“alert”])返回“function”

  2. 您已撰写 typeOf 。这工作

    function exec(method, param)
    {
        //because of typeof(window["alert"]) == "object" the actual if looks like typeof(window[method]) == 'function' || method == 'alert'
        if(typeof(window[method]) == 'function')
        {
            window[method].apply(window, [param]);
        }
    }
    
    exec("alert","hello");