zoukankan      html  css  js  c++  java
  • JavaScript中call和apply的区别

    call()方法和apply()方法的作用相同,他们的区别在于接收参数的方式不同。对于call(),第一个参数是this值没有变化,变化的是其余参数都直接传递给函数。(在使用call()方法时,传递给函数的参数必须逐个列举出来。使用apply()时,传递给函数的是参数数组)如下代码做出解释:

    //------------apply
    var obj = {
        a: 2
    }
    
    function f(s) {
        console.log(this.a, s); //2 3
        return this.a + s; //5
    }
    var f2 = function() {
        console.log(arguments); //[Arguments] { '0': 3 }
        return f.apply(obj, arguments); //obj为传入后的this
    }
    var b = f2(3);
    console.log(b);
    //-----------call
    var obj = {
        a: 2
    }
    
    function f(s) {
        console.log(this.a, s); //2 [Arguments] { '0': 3 }  s为对象
        return this.a + s; //2[object Arguments]
    }
    var f2 = function() {
        console.log(arguments); //[Arguments] { '0': 3 }
        return f.call(obj, arguments); //obj为传入后的this
    }
    var b = f2(3);
    console.log(b);
    
    
  • 相关阅读:
    golang语法要点笔记
    环境配置
    实现chrome多用户独立cookie
    Golang遇到的问题记录
    php preg_replace去除html xml 注释
    C 基础
    多种写法
    mysql 查看当前数据库
    sql group by
    sql CONCAT()
  • 原文地址:https://www.cnblogs.com/aeipyuan/p/12638625.html
Copyright © 2011-2022 走看看