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!

  • 相关阅读:
    1011. A+B和C (15)
    1010. 一元多项式求导 (25)
    1009. 说反话 (20)
    1007. 素数对猜想 (20)
    1008. 数组元素循环右移问题 (20)
    1006. 换个格式输出整数 (15)
    1005. 继续(3n+1)猜想 (25)
    算法学习(八)
    算法学习(七)
    算法学习(六)
  • 原文地址:https://www.cnblogs.com/foreverZ/p/5951911.html
Copyright © 2011-2022 走看看