Every Function object has the apply(), call(), and bind() methods. Their function is to call functions within a specific scope, effectively setting the value of the this object inside the function body to extend the scope upon which the function relies for execution.
apply(), call(), and bind() can all change the this reference of a function object.
window.name ="A";// attached to the window object's namedocument.name ="B";// attached to the document object's namevar s ={// custom object sname:"C"}var rollCall ={name:"Teacher",sayName:function(){ console.log(this.name);}}rollCall.sayName();// Teacher// applyrollCall.sayName.apply();// A // default binds to window when no arguments are passedrollCall.sayName.apply(window);// A // binds to the window objectrollCall.sayName.apply(document);// B // binds to the document objectrollCall.sayName.apply(s);// C // binds to the custom object// callrollCall.sayName.call();// A // default binds to window when no arguments are passedrollCall.sayName.call(window);// A // binds to the window objectrollCall.sayName.call(document);// B // binds to the document objectrollCall.sayName.call(s);// C // binds to the custom object// bind // the last () is to execute itrollCall.sayName.bind()();//A // default binds to window when no arguments are passedrollCall.sayName.bind(window)();//A // binds to the window objectrollCall.sayName.bind(document)();//B // binds to the document objectrollCall.sayName.bind(s)();// C // binds to the custom object
Although apply(), call(), and bind() can all change the this pointer, their usage differs.
// apply and call have different ways of passing argumentswindow.name ="Teacher";var rollCall ={sayAllName:function(...args){ console.log(this.name); args.forEach((v)=> console.log(v));}}// apply passes the arguments as an arrayrollCall.sayAllName.apply(window,["A","B","C"]);// Teacher A B C// call passes the arguments directly, separated by commasrollCall.sayAllName.call(window,"A","B","C");// Teacher A B C// bind only binds the object and does not execute immediately; it returns a function, with arguments passed in a way similar to callvar convertThis = rollCall.sayAllName.bind(window,"A","B","C");convertThis();// Teacher A B C