zoukankan      html  css  js  c++  java
  • 方法中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对象

  • 相关阅读:
    AcWing 3302. 表达式求值
    AcWing 828. 模拟栈
    六种风格时间显示
    web2.0常用配色.
    CSS浏览器兼容问题详解
    jQuery Cycle Plugin Beginner Demos
    jQuery插件Clipboard Copy(复制)。
    精通jQuery选择器使用
    jQuery插件右下角弹出信息
    CSS关于box(盒模式)的一系列问题
  • 原文地址:https://www.cnblogs.com/chenyingying0/p/12347016.html
Copyright © 2011-2022 走看看