打赏

图解avaScript中this指向(超透彻)

一个图讲清楚JavaScript中this指向:

 

说明:

(1)严格模式下,禁止this关键字指向全局对象会报错
(2)闭包中的this对象具有全局性,因此通常指向window。 
(3)优先级:new>apply/call>.调用>默认调用
(4)null/undefined,在使用apply或者call时传入null/undefined时,会使用默认调用。
<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>null/undefined参数</title>
    </head>

    <body>

        <script type="text/javascript">
            function foo(a, b) {
                console.log('a:' + a + ",b:" + b)
            }
            foo.apply(null, [1, 2])
        </script>
    </body>

</html>

 (4)箭头函数--根据外层作用域决定this指向

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <title>箭头函数的this指向</title>
    </head>

    <body>

        <script type="text/javascript">
            function foo() {
                setTimeout(() => {
                    console.log(this.a)
                }, 100)
            }
            var obj = {
                a: 2
            }
            foo.apply(obj); //2
        </script>
    </body>

</html>

 

posted @ 2018-01-24 11:16  孟繁贵  阅读(372)  评论(0编辑  收藏  举报
TOP