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

    区别

    • call(obj,arg1,arg2)

    • apply(obj,[arg1,arg2]

    • bind(this) // 不立即执行

    var obj  = {
      age: 13,
      say: function(){
        return this.age
      }
    }
    var obj2 = {
      age: 66
    }
    console.log(obj.say.apply(obj2)); / /66
    console.log(obj.say.call(obj2)); //  66
    console.log(obj.say.bind(obj2)); // function(){return this.age}
    
    
    

    用法

    • 合并两个数组
    var arr1 = [1,2];
    var arr2 = [3, 4];
    
    // 将第二个数组融合进第一个数组
    // 相当于 arr1.push(3,4);
    Array.prototype.push.apply(arr1, arr2);
    // 4
    
    arr1
    // [1, 2, 3, 4]
    
    • 获取数组中最大值
    Math.max(3,55) // 55
    
    如何获取数组中的最大值了?数组本身可没有max方法
    
    var numbers = [1,44,88]; 
    Math.max.apply(Math, numbers);   // 88  
    Math.max.call(Math, 1,44,88);  // 88
    
    // ES6
    Math.max.call(Math, ...numbers); // 88
    
    利用Math的max方法,把nums当作参数传入进去,获取最大值
    
    • 判断是否是一个对象
    function isArray(obj){ 
        return Object.prototype.toString.call(obj) === '[object Array]';
    }
    
    
    • 类数组转换为数组
    Array.prototype.slice.call(arguments)
    [].slice.call(arguments)
    Array.from(arguments)
    [...arguments]
    原因: 由于slice的实现原理
    
    // this指向类数组arguments
    function slice(start, end) { 
        var startToUse = start || 0, 
            endToUse = end || ToUint32(this.length), 
            result = []; 
        for(var i = startToUse; i < endToUse; i++) { 
            result.push(this[i]); 
        }
        return result; 
    
    
    
    • 补充什么是类数组
    1 有:指向对象元素的数字索引下标、 length 属性
    2 无:push 、shift、 forEach 以及 indexOf等数组对象具有的方法
    
    
    • 继承
    function  SuperType(){
      this.color=["red", "green", "blue"];
    }
    function  SubType(){
    
      SuperType.call(this);  // 等价于下面
    
      // obj.color = ["red", "green", "blue"]
      // this指向实例
    }
    var obj = new SubType()
    console.log(obj1.color); // [ 'red', 'green', 'blue' ]
    
    
    
  • 相关阅读:
    java容器01--初遇
    java虚拟机(1)--运行时数据区
    java虚拟机(2)--垃圾收集
    java虚拟机(3)--内存分配与回收策略
    java虚拟机(4)--类加载机制
    bash编程的信号捕获:
    awk纯干货
    shell中各种括号的作用()、(())、[]、[[]]、{}
    find
    awk
  • 原文地址:https://www.cnblogs.com/huangxingyuan/p/10873667.html
Copyright © 2011-2022 走看看