美文网首页
函数调用的方法 (apply、call)

函数调用的方法 (apply、call)

作者: 冯艳辉brook | 来源:发表于2018-01-03 18:09 被阅读0次

    参考: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function

    函数调用分4种:

    1、直接调用:

    function aaa(){this.a = 1};

    a();

    2、对象调用:

    a={aaa:function(){this.a = 1}};

    a.aaa();

    3、构造函数调用:

    function aaa(){this.a = 1}; 

    var bbb = new aaa();

    构造函数和正常的函数调用区别在于:构造函数的this指向了本实例,正常函数调用this是指向全局

    4、call,apply调用:

    call:

    fun.call(thisArg,arg1,arg2, ...)

    thisArg fun函数运行时指定的this值,如果这个函数处于非严格模式下,则指定为null和undefined的this值会自动指向全局对象

    arg1, arg2, ...  :    指定的参数列表。


    apply:

    fun.apply(thisArg, [argsArray])

    thisArg :fun函数运行时指定的this值,如果这个函数处于非严格模式下,则指定为null和undefined的this值会自动指向全局对象

    argsArray : 参数列表数组。

    function aaa(age){

        this.age = age;

        console.log(this.name, this.age)

    }

    var b = {name:"content"};

    aaa.call(b, 12);// content 12

    aaa.apply(b, [12]);// content 12

    call和apply的区别在于第二个参数call是传按顺序传参,而apply是传一个数组参数

    相关文章

      网友评论

          本文标题:函数调用的方法 (apply、call)

          本文链接:https://www.haomeiwen.com/subject/wpcknxtx.html