The four call modes of the function and the this pointing to it
- 2021-07-12 04:38:22
- OfStack
Type 1: Function direct execution mode
function add(a,b){
console.log(this);
return a+b;
}
add(10,20)//this===window
Type 2: Call mode of object method
var obj={
name:'aaa',
age:20,
said:function(){
console.log(this);
}
}
obj.said();//this===obj , here this Refers to the callee
Type 3: The invocation mode of the constructor
function School(){
this.said=function(){
console.log(this);
}
}
var nanj=new School();
nanj.said();// Object calls its own method, this===nanj , similar to the above
Type 4: call and apply call modes
function change(a,b){
this.detial=a*b;
console.log(this);
}
var p={};
change.call(p,4,5);// Here this===p
console.log(p.detial);
var q=[];
change.call(q,5,10)//this===q
console.log(q.detial);
//apply And call1 Sample usage, just apply No. 1 2 Parameters are passed in an array
var arr=[];
change.apply(arr,[10,10]);//this===arr
console.log(arr.detial);
var str={};
change.apply(str,[20,20]);//this===str
console.log(str.detial);