• call apply bind的用法


    在Javascript 中,call、apply 和bind 是Function对象自带的三个方法,这个三个方法主要作用是改变函数中的this指向。

    apply 、 call 、bind 三者都是用来改变函数的this对象的指向的;
    apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文(函数的每次调用都会拥有一个特殊值——本次调用的上下文(context)——这就是this关键字的值。);
    apply 、 call 、bind 三者都可以利用后续参数传参;
    bind 是返回对应函数,便于稍后调用;apply 、call 则是立即调用 

    call();

    语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])

    定义:调用一个对象的一个方法,以另一个对象替换当前对象

    说明:call方法可以用来代替另一个对象调用一个方法

    call方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj指定的新对象

    thisObj的取值有以下4种情况:
    (1) 不传,或者传null,undefined, 函数中的this指向window对象
    (2) 传递另一个函数的函数名,函数中的this指向这个函数的引用
    (3) 传递字符串、数值或布尔类型等基础类型,函数中的this指向其对应的包装对象,如 String、Number、Boolean
    (4) 传递一个对象,函数中的this指向这个对象

    function a(){   
      console.log(this);   //输出函数a中的this对象
    }       
    function b(){}       
    var c={name:"call"};    //定义对象c  
    a.call();   //window
    a.call(null);   //window
    a.call(undefined);   //window
    a.call(1);   //Number
    a.call('');   //String
    a.call(true);   //Boolean
    a.call(b);   //function b(){}
    a.call(c);   //Object

    function class1(){   
      this.name=function(){   
        console.log("我是class1内的方法");   
      }   
    }   
    function class2(){ 
      class1.call(this);  //此行代码执行后,当前的this指向了class1(也可以说class2继承了class1)   
    }   
    
    var f=new class2();   
    f.name();   //调用的是class1内的方法,将class1的name方法交给class2使用
    例子:
    function eat(x,y){   
      console.log(x+y);   
    }   
    function drink(x,y){   
      console.log(x-y);   
    }   
    eat.call(drink,3,2) //5


    function Animal(){   
      this.name="animal";   
      this.showName=function(){   
        console.log(this.name);   
      }   
    }   
    function Dog(){   
      this.name="dog";   
    }   
    var animal=new Animal();   
    var dog=new Dog();       
    
    animal.showName.call(dog);
    
    输出:dog








  • 相关阅读:
    Linux命令之查看cpu个数_核数_内存总数
    Python文件操作大全,随机删除文件夹内的任意文件
    Python文件操作:同一个文件进行内容替换
    异步请求Python库 grequests的应用和与requests库的响应速度的比较
    查询MySQL某字段相同值得重复数据
    /var/redis/run/redis_6379.pid exists, process is already running or crashed的解决办法
    人工智能----TensorFlow开篇简介
    Centos6.5+Python2.7 +ffmpeg+opencv2自动安装脚本
    决策统计---指标六要素
    大数据应用分类
  • 原文地址:https://www.cnblogs.com/qingcui277/p/10412984.html
Copyright © 2020-2023  润新知