js the Function object --call, apply and bind

Function object -call, apply and bind

The role of these three objects is to change this point in the function
such as:

function f1(a,b){
	console.log(a + b);
}
f1(1,2); //3
f1.call(null,1,2); //3
f1.apply(null,[1,2]);//3
function f2(a,b){
	console.log(a + b);
}·
f2.call(obj,1,2);
//这个时候里面的this的指向已经不是window了已经换为了obj

However, the difference between call and apply is to apply must be placed within the array.
If the function is not parameter, then the first call and apply can not pass parameters, this default window if passed null, then also the default window;
if there are parameters, then you first need to pass parameters and must be an object or pass null, otherwise will complain or appear NAN

What practical effect call and apply what is it?

1. Method borrow
2.js inheritance

1.)方法借用
//求最大数
Math.max(1,2,3,55,77)//77
Math.max([1,2,3,55,77])//报错

Math.max.apply(null,[1,2,3,55,77]);//77
//等同于
var arr = [1,2,3,55,77];
Math.max.apply(null,arr);//77


//2.把伪数组转化为数组
var wsz = {0,"123",1,"asd",2,"123",length:3};
var arr = [].slice.call(wsz);
Published 84 original articles · won praise 204 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_44983621/article/details/103443814