方法中this指向的问题

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
    <button class="btn">按钮</button>

    <script src="../js/jquery.js"></script>
    <script>
        var obj={
            show:function(){
                console.log(this,1);
            },
            hide:function(){
                console.log(this,2);
            }
        }

        //这次只是绑定了事件,真正调用时是在hover的时候
        //因此调用这个方法的实际是hover的元素
        $(".btn").hover(obj.show,obj.hide);//this指向调用obj.show这个方法的元素

    </script>
</body>
</html>

这里只是绑定了事件,函数真正执行是在元素被hover的时候,因此this指向调用该方法的元素

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
</head>
<body>
    <button class="btn">按钮</button>

    <script src="../js/jquery.js"></script>
    <script>
        var obj={
            show:function(){
                console.log(this,1);
            },
            hide:function(){
                console.log(this,2);
            }
        }

        $(".btn").hover(function(){
            obj.show();//方法是obj直接调用的,因此this指向obj
        },function(){
            obj.hide();
        });
    </script>
</body>
</html>
复制代码

这里的方法是在匿名函数中直接调用的(加了()小括号表示调用)

因此this指向调用该方法的obj对象

原文地址:https://www.cnblogs.com/ZXH-null/p/12350175.html