javascript笔记---改变函数内部this指向call(),apply(),bind()方法

    科技2022-07-13  130

    call()

    call() 方法调用一个对象。简单理解为调用函数的方式,但是它可以改变函数的 this 指向。 fun.call(thisArg, arg1, arg2, ...)

    1,thisArg:在 fun 函数运行时指定的 this 值 2,arg1,arg2:传递的其他参数 3, 返回值就是函数的返回值,因为它就是调用函数 4, 因此当我们想改变 this 指向,同时想调用这个函数的时候,可以使用 call,比如继承

    var o = { name: "andy", } function fn(a, b) { // this.name=name; console.log(this); console.log(a + b); } // call第一可以调用函数,也可以改变函数的this指向 //将fn函数中的this指向o这个对象, fn.call(o, 1, 2);

    输出:

    call来继承

    function Father(name, id) { this.name = name; this.id = id; } function Son(name, id) { // 这里是this指向Son,所以意思是将Fathe的this指向改成指向Son的 Father.call(this, name, id) } var son = new Son("刘德华", 18); console.log(son);

    输出:

    apply()

    fun.apply(thisArg, [argsArray])

    1, thisArg:在fun函数运行时指定的 this 值 2,argsArray:传递的值,必须包含在数组里面 3,返回值就是函数的返回值,因为它就是调用函数 4,因此 apply 主要跟数组有关系,比如使用 Math.max() 求数组的最大值

    var e = { id: 2, } function fathe() { console.log(this); } //apply可以直接调用函数,也可以改变函数里面this的指向 fathe.apply(); fathe.apply(e);

    输出:

    apply()通过内置数学函数对象求最大值

    var ar = [2, 98, 20, 53]; console.log(Math.max.apply(Math, ar)); console.log(Math.min.apply(Math, ar)); console.log(Math.max(...ar)); console.log(Math.min(...ar));

    输出:

    bind()

    fun.bind(thisArg, arg1, arg2, ...

    1,thisArg:在 fun 函数运行时指定的 this 值 2,arg1,arg2:传递的其他参数 3,返回由指定的 this 值和初始化参数改造的原函数拷贝 4,因此当我们只是想改变 this 指向,并且不想调用这个函数的时候,可以使用 bind

    var ab={ name:"andy", } function fn(a,b){ console.log(this); console.log(a+b); } //bind不会直接调用函数,而是返回一个改变了this的新函数 var f= fn.bind(ab,2,3); f();

    输出:

    Processed: 0.015, SQL: 8