call、apply和bind的区别

Call和Apply的比较

相同点:两个方法产生的作用是完全一样的,都用来改变当前函数调用的对象。

不同点:调用的参数不同,比较精辟的总结:

foo.call(this,arg1,arg2,arg3) == foo.apply(this, arguments)==this.foo(arg1, arg2, arg3)
function add(c,d){
    return this.a + this.b + c + d;
}

var s = {a:1, b:2};
console.log(add.call(s,3,4)); // 1+2+3+4 = 10
console.log(add.apply(s,[5,6])); // 1+2+5+6 = 14s

bind和Call(Apply)的区别

bind方法返回的是一个改变this指向的函数

var obj = {
    name: "jesse",
    fn: function (age) {
        console.log("name is "+this.name+" , age is "+age)
    }
}

var alvin = {
    name: "alvin"
}

obj.fn.call(alvin, 11);   //  name is alvin , age is 11
obj.fn.bind(alvin, 11);   //  ƒ (age) { console.log("name is "+this.name+" , age is "+age) }
obj.fn.bind(alvin, 11)(); //  name is alvin , age is 11

results for ""

    No results matching ""