zoukankan      html  css  js  c++  java
  • jquery中的call和apply方法

    call方法:
    语法:call([thisObj[,arg1[, arg2[,   [,.argN]]]]])
    定义:调用一个对象的一个方法,以另一个对象替换当前对象。
    说明:
    call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。
    如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

    apply方法:
    语法:apply([thisObj[,argArray]])
    定义:应用某一对象的一个方法,用另一个对象替换当前对象。
    说明:
    如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。
    如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。

    1.    
    2. <script language="javascript"><!--  
    3.     
    4. /**定义一个animal类*/    
    5. function Animal(){     
    6.     this.name = "Animal";     
    7.     this.showName = function(){     
    8.         alert(this.name);     
    9.     }     
    10. }     
    11. /**定义一个Cat类*/    
    12. function Cat(){     
    13.     this.name = "Cat";     
    14. }     
    15.     
    16. /**创建两个类对象*/    
    17. var animal = new Animal();     
    18. var cat = new Cat();     
    19.     
    20. //通过call或apply方法,将原本属于Animal对象的showName()方法交给当前对象cat来使用了。     
    21. //输入结果为"Cat"     
    22. animal.showName.call(cat,",");     
    23. //animal.showName.apply(cat,[]);     
    24.       
    25.     
    26.   
    27. / --></script>   

    以上代码无论是采用animal.showName.call或是animal.showName.apply方法,运行的结果都是输出一个"Cat"的字符串。说明showName方法的调用者被换成了cat对象,而不是最初定义它的animal了。这就是call和apply方法的妙用!

     

    如果cat类中没有定义 this.name = "Cat";,那么执行的发放中弹出的将是NaN对象,不会用Animal中的this.name。其中call和apply中的第二个参数是showname中的options参数。

     

     

    如:

    $.tukibox = function(method) {
    if (methods[method]) {
    return methods[ method ].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || ! method) {
    return methods.init.apply(this, arguments);
    } else {
    $.error('Method ' + method + ' does not exist on jQuery.tukibox');
    }
    };

    上面的call中,就是调用Array的slice方法,传入两个参数作为slice的参数。apply当然是让当前对象调用methods对象中的指定方法或者是init初始化方法。

     

  • 相关阅读:
    Linux Network Related Drive
    Deformity ASP/ASPX Webshell、Webshell Hidden Learning
    PostgreSQL Reading Ad Writing Files、Execution System Instructions Vul
    Linux下修改进程名称
    karottc A Simple linux-virus Analysis、Linux Kernel <= 2.6.37
    python grammar、C/C++ Python Parsing Engine
    Java unserialize serialized Object(AnnotationInvocationHandler、ysoserial) In readObject() LeadTo InvokerTransformer(Evil MethodName/Args)
    Redis未授权访问漏洞分析
    Automated CMS category, version identification (CMS vulnerability detection)
    Linux process authority、the security risks in running process with high authority
  • 原文地址:https://www.cnblogs.com/xingmeng/p/2751024.html
Copyright © 2011-2022 走看看