huoxiangdong / Blog

学习记录
0 stars 0 forks source link

apply 、 call 、bind #18

Open huoxiangdong opened 6 years ago

huoxiangdong commented 6 years ago

apply 、 call 、bind 三者都是用来改变函数的this对象的指向的; apply 、 call 、bind 三者第一个参数都是this要指向的对象,也就是想指定的上下文; apply 、 call 、bind 三者都可以利用后续参数传参; bind是返回对应函数,便于稍后调用;apply 、call 则是立即调用

huoxiangdong commented 6 years ago

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

huoxiangdong commented 6 years ago
huoxiangdong commented 6 years ago
huoxiangdong commented 6 years ago
huoxiangdong commented 6 years ago
  var a = {
        name : "Cherry",
        fun1: function () {
            console.log(this.name)
        },
        fun2: function () {
            setTimeout(function () {
                this.fun1() // 知道了this是谁,在哪个上下文下运行 a.fun1
            }.apply(a),100);             
        }
    };
huoxiangdong commented 6 years ago
var a ={
        name : "Cherry",
        fn : function (a,b) {
            console.log( a + b)
        }
    }
console.log(a.fn.bind(a,1,2))
pint:
ƒ (a,b) {
            console.log( a + b)
        }
huoxiangdong commented 6 years ago
huoxiangdong commented 6 years ago
Array.prototype.slice.call(arguments);

arguments.Array.prototype.slice 

arguments.slice
huoxiangdong commented 6 years ago