zoukankan      html  css  js  c++  java
  • 夺命雷公狗---javascript NO:32 Call/Apply方法

    行内绑定中this指向:全局window对象

    动态绑定中this指向:当前要操作的dom对象

    构造器中的this指向:谁实例化构造器那么其内部的this就指向谁

    1、为什么需要Call与Apply方法

    问题:我们可以不可以手工改变函数内部的this指向?答:可以,使用Call或Apply方法

    2、如何定义Call与Apply方法

    call([thisObj[,arg1[,arg2[,argN]]]])

    参数说明:

    函数.call(thisObj,arg1,arg2,arg3…)

    thisObj :要指向的Obj对象

    arg1,arg2,arg3 :要传递的参数

    apply([thisObj[,argArray]])

    参数说明:

    thisObj :要指向的Obj对象

    argArray :要传递的参数,要求格式为数组

    Call与Apply方法区别?

    在功能上,两者效果完全一致,都是用于改变函数内部的this指向

    在语法上,两者语法略有不同

    3、为对象添加一个speak成员方法

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=’utf-8′>
    <title></title>
    </head>
    <body>
    <script>
    //定义一个公用的说话方法
    function speak(){
    alert(this.name+this.age);
    }
    function person(){}
    //通过person构造器创建对象
    var p1 = new person();
    p1.name = ‘zhangsan';
    p1.age = ’22′;
    //通过call方法调用speak方法
    speak.call(p1);
    var p2 = new person();
    p2.name = ‘lisi';
    p2.age =55′;
    //通过apply方法调用speak说话方法
    speak.apply(p2);
    </script>
    </body>
    </html>

    4、call与apply方法执行流程

    1)改变函数内部的this指向

    2)调用函数

    5、实现为speak方法传参

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=’utf-8′>
    <title></title>
    </head>
    <body>
    <script>
    //定义一个公用的说话方法
    function speak(email,address){
    alert(this.name+this.age+email+address);
    }
    function person(){}
    //通过person构造器创建对象
    var p1 = new person();
    p1.name = ‘zhangsan';
    p1.age = ’22′;
    //通过call方法调用speak方法
    speak.call(p1,’123.@.163.com’,’广东省广州市’);
    var p2 = new person();
    p2.name = ‘lisi';
    p2.age =55′;
    //通过apply方法调用speak说话方法
    speak.apply(p2,[‘5566@qq.com’,’广东省深圳市’]);
    </script>
    </body>
    </html>

    6、案例:同时改变文字大小与颜色特效

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=’utf-8′>
    <title></title>
    <script>
    function fn1(){
    this.style.color = ‘red';
    }
    function fn2(){
    this.style.fontSize = ’30px';
    }
    window.onload = function(){
    document.getElementById(‘result’).onclick = function(){
    fn1.call(this);
    fn2.apply(this);
    }
    }
    </script>
    </head>
    <body>
    <div id=’result’>call与apply方法主要功能是改变函数内部的this指向</div>
    </body>
    </html>
  • 相关阅读:
    Struts2+Spring3+Mybatis3开发环境搭建
    spring+struts2+mybatis
    【LeetCode】Populating Next Right Pointers in Each Node
    【LeetCode】Remove Duplicates from Sorted Array
    【LeetCode】Remove Duplicates from Sorted Array II
    【LeetCode】Binary Tree Inorder Traversal
    【LeetCode】Merge Two Sorted Lists
    【LeetCode】Reverse Integer
    【LeetCode】Same Tree
    【LeetCode】Maximum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/leigood/p/5032044.html
Copyright © 2011-2022 走看看