zoukankan      html  css  js  c++  java
  • $.proxy的使用

    $.proxy()是jquery的一个方法。是一个改变this指向的方法。

    在某些情况下,我们调用Javascript函数时候,this指针并不一定是我们所期望的那个。例如:

    //正常的this使用
     2 $('#myElement').click(function() {
     3 
     4     // 这个this是我们所期望的,当前元素的this.
     5 
     6     $(this).addClass('aNewClass');
     7 
     8 });
     9 
    10 
    11 //并非所期望的this
    12 $('#myElement').click(function() {
    13 
    14     setTimeout(function() {
    15 
    16           // 这个this指向的是settimeout函数内部,而非之前的html元素
    17 
    18         $(this).addClass('aNewClass');
    19 
    20     }, 1000);
    21 
    22 });

    这时候怎么办呢,通常的一种做法是这样的:

    复制代码
     1 $('#myElement').click(function() {
     2     var that = this;   //设置一个变量,指向这个需要的this
     3 
     4     setTimeout(function() {
     5 
     6           // 这个this指向的是settimeout函数内部,而非之前的html元素
     7 
     8         $(that).addClass('aNewClass');
     9 
    10     }, 1000);
    11 
    12 });
    复制代码

    但是,在使用了jquery框架的情况下, 有一种更好的方式,就是使用$.proxy函数。

    jQuery.proxy(),接受一个函数,然后返回一个新函数,并且这个新函数始终保持了特定的上下文(context )语境。

    有两种语法:

    复制代码
    jQuery.proxy( function, context )
    /**function将要改变上下文语境的函数。
    ** context函数的上下文语境(`this`)会被设置成这个 object 对象。
    **/
    
    jQuery.proxy( context, name )
    /**context函数的上下文语境会被设置成这个 object 对象。
    **name将要改变上下文语境的函数名(这个函数必须是前一个参数 ‘context’ **对象的属性)
    **/
    复制代码

    上面的例子使用这种方式就可以修改成:

    复制代码
    $('#myElement').click(function() {
    
        setTimeout($.proxy(function() {
    
            $(this).addClass('aNewClass');  
    
        }, this), 1000);
    
    
    
    });




    参考 博文https://www.cnblogs.com/hongchenok/p/3919497.html
  • 相关阅读:
    AngularJS Insert Update Delete Using PHP MySQL
    Simple task manager application using AngularJS PHP MySQL
    AngularJS MySQL and Bootstrap Shopping List Tutorial
    Starting out with Node.js and AngularJS
    AngularJS CRUD Example with PHP, MySQL and Material Design
    How to install KVM on Fedora 22
    Fake_AP模式下的Easy-Creds浅析
    河南公务员写古文辞职信
    AI
    政协委员:最大愿望是让小学生步行上学
  • 原文地址:https://www.cnblogs.com/shj-com/p/10299737.html
Copyright © 2011-2022 走看看