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

    • 经常混淆这两个方法,在此做个总结
    • 每个函数都包含两个非继承而来的方法:call()方法和apply()方法。

    相同点

    • 这两个方法的作用是一样的,即改变this的指向。

    不同点

    接收参数的方式不同

    • 两个方法的第一个参数一般写的都是函数运行的作用域(this),可以为空,那当前函数运行的作用域就为window,但apply方法必须填上null,call不需要填
    • 示例:
    console.log(Math.max.call(1,5,7));
    console.log(Math.max.apply(null,[1,5,7]));
    
    • 接收的第二个参数也不同,apply方法的第二个参数必须是数组形式,而call方法不需要
    • 举例:
     function add(c,d){
            return this.a + this.b + c + d;
        }
        var s = {a:1, b:2};
        console.log(add.call(s,3,4)); // 1+2+3+4 = 10
        console.log(add.apply(s,[5,6])); // 1+2+5+6 = 14 
    
  • 相关阅读:
    select函数
    ascy_finder|base|cookie 代码测试
    正则表达式之道
    教务系统破解
    jquery API
    test
    如何获取和发送Http请求和相应
    header中ContentDisposition的作用
    Performance Testing 系列
    LINQ
  • 原文地址:https://www.cnblogs.com/wan-fei/p/8386432.html
Copyright © 2011-2022 走看看