美文网首页javascript基础入门
Javascript - 函数的call,apply,bind

Javascript - 函数的call,apply,bind

作者: 厦门_小灰灰 | 来源:发表于2019-11-18 19:03 被阅读0次

call(), apply(), bind()三个方法属于函数的内建函数,任何一个函数都可以调用这三个方法;

通过这三个方法中的任何一个,可以改变某个函数运行时的上下文(context)。可以理解为改变函数体内部 this 的指向。

接下来分别介绍这三个方法的使用:

call

使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数;

语法:

/*

    thisArg:  函数运行时指定的 this 值,
        当thisArg的值为:undefined 或者 null,this = window
        当thisArg的值为: number 或者 boolean 或者 string, this为对应的包装类,如new Number(), new Boolean(), new String()

    arg1, arg2, ...:参数列表,参数通过逗号隔开

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

apply

调用一个具有给定this值的函数,以及作为一个数组(或类数组对象)提供的参数。

语法:

/*

    thisArg:  函数运行时指定的 this 值,
        当thisArg的值为:undefined 或者 null,this = window
        当thisArg的值为: number 或者 boolean 或者 string, this为对应的包装类,如new Number(), new Boolean(), new String()

    argsArray:参数数组,参数通过数组装起来

*/
func.apply(thisArg, [argsArray])

bind

创建一个新的函数

语法:跟call()方法是一样的。

返回值:返回一个原函数的拷贝,并拥有指定的this值和初始参数。

简单示例:

var name = "OutterName";

var obj = {
    name: 'ObjName',
}

function printName(age) {
    console.log("my name is " + this.name + ",age = " + age);
}

printName.call(null, 20);
printName.apply(obj, [21]);
printName.bind(obj)(22);

结果:


结果.png

注意:call()方法的作用和 apply() 方法类似,区别就是call()方法接受的是参数列表,而apply()方法接受的是一个参数数组。

更多的方法,在后续用到的时候,在进行补充;

相关文章

网友评论

    本文标题:Javascript - 函数的call,apply,bind

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