Difference between bind, apply and call method?

前端 未结 3 462
刺人心
刺人心 2020-12-28 09:05

I was searching in stackoverflow and the web, could not get proper results or explanation siting difference between these three methods.

As far as i understand, the

3条回答
  •  感动是毒
    2020-12-28 09:57

    bind creates a new function with the same function body and then returns the new function
    call calls the same function in a different passed context and the parameters have to be explicitly written apply calls the same function in a different passed context but the parameters have to be passed in a an array

    var f = function(p1, p2) {
        var s = this;
    }
    
    var newFunc = f.bind(window, 1, 2);
    // here newFunc is a function which when you will call will have this as window and p1 = 1 and p2 = 2
    
    f.call(window, 1, 2);
    // by executing this line this = window p1 = 1 and p2 = 2
    
    f.call(document, 2, 3);
    // by executing this line this = document p1 = 2 and p2 = 3
    
    f.apply(window, [1, 2]);
    // by executing this line this = window p1 = 1 and p2 = 2
    

提交回复
热议问题