js 中 this 的指向问题

2017-11-11  本文已影响14人  想做一个画家
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <!-- this 如果没有被调用的话 是没有指向谁这一说的 -->
    <button id='btn'>点我</button>
    <!-- 1、this 指的是调用当前方法(函数)的那个对象,也就是说函数在谁那被调用,this就指的是谁。 -->
    <script>
        

        var oBtn = document.getElementById('btn');

        // oBtn.onclick = function(){
        //    console.log(this); // oBtn
        // }

        // 很容易看出,函数是在按钮对象被点击的时候调用,所以 this 指的是 obtn
        

     // 2 当函数里面嵌套函数的时候,嵌套的那个函数里面的this指的是window, 不要过分深究这个原因,因为这是JS的一个特性。
        //   oBtn.onclick = function () {
        //         console.log(this); // 这里还是 oBtn

        //         fn();
        //     }

        //     function fn(){
        //         console.log(this) // window 
        //     }
 
            // 3 、对于上述情况,当我们需要 fn 里面的 this 指向按钮的时候怎么办呢,这个时候有两种方法。
            //     1) 将this作为参数传函数去
            //     2) 将this保存起来赋给另一个变量
            //     来看两个例子: 

            //---------------------------------------------------------

            // 方法一
            // oBtn.onclick = function () {
            //         console.log(this); // oBtn

            //         fn(this);
            //     }

            //     function fn(obj) {
            //         console.log(obj) // oBtn
            //     }
            //---------------------------------------------------------

            // 方法二
             var _that =null;
             oBtn.onclick = function () {
                    console.log(this); // oBtn

                    _that = this;

                    fn();

                }

                function fn() {
                    console.log(_that) // oBtn
                }


    </script>



</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读