1

func.apply(null, arr)您能解释一下使用和func.apply(this, arr)在下面的代码示例中的区别吗?

var Foo = function() {
    function useMe(a, b, c)
    {
        document.body.innerHTML =
            '<p>a: ' + a + '<br>b: ' + b + '<br>c: ' + c + '</p>'
    }

    function go()
    {
        var arr = ['foo', 'bar', 'baz']
        useMe.apply(null, arr)
    }

    return {
        go: go,
        useMe: useMe
    }
}()

Foo.go()

来源:http: //jsfiddle.net/YQsaJ/

var Foo = function() {
    function useMe(a, b, c)
    {
        document.body.innerHTML =
            '<p>a: ' + a + '<br>b: ' + b + '<br>c: ' + c + '</p>'
    }

    function go()
    {
        var arr = ['foo', 'bar', 'baz']
        useMe.apply(this, arr) // USING this INSTEAD OF null
    }

    return {
        go: go,
        useMe: useMe
    }
}()

Foo.go()

JSFiddle:http: //jsfiddle.net/3DvtA/

我知道当null用作函数的第一个参数时,apply全局对象,即window用作. 对于像上面的代码这样简单的用法,我们作为函数的第一个参数传递什么真的很重要吗?thisuseMeapply

4

2 回答 2

2

所有函数都有一个所谓的上下文。这个上下文是一个对象并且存在于this变量中。

警告“Hello World”的示例:

function hello() {
  alert(this.greeting);
}

hello.apply({greeting: "Hello World"});

您的函数无法访问this,因此在您的上下文中指定null还是this都没有关系。

从 ES 5 严格模式开始,window它不再是函数的标准上下文,而是包含 value undefined

于 2013-09-22T16:02:17.297 回答
2

第一个参数applythis在函数调用中使用的值。既然useMe不使用this,你提供什么都没关系。提供nullundefined告诉apply使用全局对象(松散模式)或undefined(严格模式)。

于 2013-09-22T16:02:45.563 回答