• 简述Javascript中call apply


     1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    2 <html>
    3 <head>
    4 <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    5 <title>Insert title here</title>
    6 </head>
    7 <body>
    8 <input type="text" id="testCall" onclick="test()">
    9
    10 </body>
    11 <script type="text/javascript">
    12 function add(a,b)
    13 {
    14 this.name = 'add';
    15 alert(a+b);
    16 alert(this.name);
    17 }
    18
    19 function sub(a,b)
    20 {
    21 this.name = 'sub';
    22 alert(a-b);
    23 alert(this.name);
    24 }
    25
    26 function test()
    27 {
    28 add.call(sub,3,1);
    29 }
    30 </script>
    31 </html>

    在为dom元素添加事件时会用到

    call体现了javascript的动态语言性质(周爱明老师书上有讲,犀牛书也讲到了)

    通过call也可以实现javascript的继承

    解释下28行

    结果是4  然后 sub

    其实相当于调用了add这个方法,并将3和1这两个参数传给add方法

    但是要注意的是 还有个额外的 第一个参数sub

    这个参数是指调用add时 涉及到的this指向谁,这里指向sub

    如果你要他指向自身(add),那么第一个参数(sub那位置)传null也是可以的

    apply与call不一样的是

    是在接受的参数方面

    第一个参数是与call一样的

    只是apply方法后面接受一个数组,而不是像call那样展开写的参数列表

    扩展阅读:

    javascript添加事件。兼容火狐IE

    http://luoyahu.iteye.com/blog/680147

    建议 第八行代码写成

     handler.call(null,argsObject, e); 



  • 相关阅读:
    解决phpmailer可以在windows下面发送成功, 在linux下面失败的问题
    centos安装svn
    linux下面配置安装nodejs+npm
    排序与搜索
    链表
    栈和队列
    顺序表
    初识算法、数据结构
    Linux_02
    Linux_01
  • 原文地址:https://www.cnblogs.com/simoncook/p/2308077.html
Copyright © 2020-2023  润新知