zoukankan      html  css  js  c++  java
  • $.proxy() 的妙用

    $.proxy() 最主要就是用来修改函数执行时的上下文对象的。

    先看以下情景:

    <div id="panel" style="display:none;">
        <button class="close">消失</button>
    </div>
    <script>
    $("#panel").fadeIn(function () {
      $('.close').click(function () {
        $(this).fadeOut(); // 其实这里我想让 #panel 隐藏来着
      });
    });
    $('#panel').click(function() {
      setTimeout(function() {
        $(this).addClass('aNewClass'); // 这个 this 根本就不对嘛
      }, 1000);
    });
    </script>
    

    打断一下...这里用 var $this = $(this); 来处理也可以呀。

    妈蛋,还让不让我讲了啊喂。骚年郎,你是还没接触到 this 这门艺术的高深之处才会这样觉得,将 this 不去标量化才是我们装逼的价值。

    不但少了个生成变量的性能输出,还避免了变量名耦合,最极致的莫过于提高了复用性...

    看一眼改版后的代码

    $("#panel").fadeIn(function(){
        $('.close').click($.proxy(HidePanel, this));
        // 相比这个 $('.close').click(function(){HidePanel()}); 优美很多
    });
    function HidePanel() {
        $(this).fadeOut();
    }
    $('#panel').click(function() {
      setTimeout($.proxy(function() {
        $(this).addClass('aNewClass');
      }, this), 1000);
    });
    

      

    上文说的是 $.proxy(fn, context) 用法,

    而 $.proxy(context, name) 用法感觉更多的用在对象上,个人用的较少,因为感觉 new 一个对象函数要更爽(而 new 出来的 this 肯定不会乱了呀),不过还是列一下吧

    var person = {
      name: "zyh",
      say: function(event) {alert(this.name)},
    }
    // $('#test').click(person.say) 显然有问题
    $('.test').click($.proxy(person,'say'));
    

    喊口号:热爱前端,活用 this!

  • 相关阅读:
    10年后我又来看看我自己!
    KubernetesKuboard
    VSCode SSH 免密登录
    Windows Terminal 使用 PuTTY 连接 COM 串口
    PuTTY SSH 免密登录
    FastDDS 安装过程的坑🕳坑🕳坑🕳坑🕳坑🕳坑🕳
    Samba 安装、配置、共享 home 目录、创建用户、设置密码、映射盘符
    Win10 恢复快捷方式小箭头
    CSAPP 并发编程读书笔记
    修改 VSCode 终端配色
  • 原文地址:https://www.cnblogs.com/foreverZ/p/5951911.html
Copyright © 2011-2022 走看看