Preface
During the interview process, many new questions will appear to allow you to expand new knowledge, and you will also discover points that you have overlooked in your studies.
In an interview two days ago, the interviewer asked about the difference between call, apply and bind. In fact, we should also understand what the interviewer wants to ask more, that is, what is expanded.
call
call is a method that can be called by all functions. It is a method in Function.prototype
function
Call the function
Change this as the first parameter
Pass the parameter after the second parameter All number of parameters
Case
function fn1(){ console.log(1); } function fn2(){ console.log(2); } fn1.call(fn2); //输出 1 fn1.call.call(fn2); //输出 2
Analysis:
The first line of output, calling fn1
And point this
to the second line of output of fn2
. In fact, the execution of call()
is the key, and it is involved here## The mechanism of #Function.prototype.call(), it just treats the code segment before
.call() as a variable, and points the passed code segment to
this, Then fn1.call points to
fn2, so it is relative to
fn2.call(), except that the
this passed here is
window
function Father(uname,age){ this.uname= uname; this.age=age; } Father.prototype={ constructor:Father, sing:function(){ console.log("唱跳rap"); } } function Son(){ Father.call(this,uname,age) } Son.prototype=new Father();
Function.prototype
let arr=Array.of(2,42,56,89,1,24,56,22) let max=Math.max.apply(Math,arr) console.log(max);
Function.prototype
let btns=document.querySelectorAll("button") for(let btn of btns){ btn.onclick=function(){ this.disabled=true; setTimeout(function(){ this.disabled=false; }.bind(this),2000); } }
this and does not call the function. But in fact, if you use the arrow function, it will be much simpler because
this of the arrow function is related to the context
this. This case is intended to help us understand
How to use bind, then attach the arrow function writing method below
let btns=document.querySelectorAll("button") for(let btn of btns){ btn.onclick=function(){ this.disabled=true; setTimeout(()=>{ this.disabled=false; },2000); } }
JS Tutorial"
The above is the detailed content of The differences and principles of call, apply and bind in js and the advanced application of extensions. For more information, please follow other related articles on the PHP Chinese website!