zoukankan      html  css  js  c++  java
  • call 与 apply

    一、call和apply的使用

    obj.call(thisObj,  arg1, arg2, ...);
    obj.apply(thisObj, [arg1, arg2, ...]);

    将obj绑定到thisObj, 此时 thisObj 拥有了obj的属性和方法,即 thisObj 【继承】了obj的属性和方法

     绑定后,立即执行函数

    注意:在非严格模式下,thisObj指定为null或undefined,会自动指向全局对象(window对象)

    1)调用普通函数

    function add (x, y) {
        return x+y;  
    }
    
    function sub (x, y) {
       return x-y;  
    }
    
    add(5,3); //8
    
    add.call(sub , 5, 3); // 8
    add.apply(sub,  [5, 3]); // 8
    
    sub.call(add, 5, 3); //2
    sub.apply(add, [5, 3]); // 2

     2)调用原生对象的方法

    var a = {0:1, 1:"yjc", length: 2}; 
    
    a.slice(); //TypeError: a.slice is not a function
    
    Array.prototype.slice.call(a);//[1, "yjc"]

    3)继承

    var aa = function () {
     this.name = 'jack';
     this.age = 20;
    }
    
    var bb = {}
    
    aa.apply(bb);  或 aa.call(bb);
    
    console.log(bb); // {name: 'jack', age: 20 }

    区别

    call接收的是连续参数

    apply接收的是数组

    二、bind的使用

    obj.bind(thisObj,  arg1, arg2, ...);

    把obj绑定到thisObj,这时候thisObj具备了obj的属性和方法。与call和apply不同的是,bind绑定后不会立即执行。

    同样是add()和sub()

    add.bind(sub, 5, 3); // function ...
    
    add.bind(sub, 5, 3)(); // 8
  • 相关阅读:
    js中'1'到1的转换
    js类型判断
    docker安装mysql5.7
    HMM隐马尔可夫模型学习
    [python] wgs84转为gcj02坐标
    python经纬度转enu坐标
    Centos7开放及查看端口
    设计模式笔记
    npm 全面介绍
    Yarn 安装与使用详细介绍
  • 原文地址:https://www.cnblogs.com/yangstar90/p/6806909.html
Copyright © 2011-2022 走看看