call,apply,bind handwritten code

Call, apply, and bind are all the problems of changing this point. Point this in
the method to the first parameter in call. When the first parameter is null or undefined, it points to window by default;
after the first parameter in call, it must be passed. The list of parameters to the method.

Apply is similar to call, but the difference lies in the inconsistent form of the parameters passed to the method. The parameters passed to the method by apply are in the form of an array.

When call and apply change the this point of the
method, they will execute the method at the same time; bind does not execute the method, but returns the new method after changing the this point.

Handwritten call code

function myCall(fn,thisObj,...args){
    
    
	thisObj = thisObj?thisObj:window
	thisObj.fn = fn
	let result = thisObj.fn(...args)
	delete thisObj.fn
	return result
}

Handwritten apply code

args: is an array

function myApply(fn,thisObj,args){
    
    
	thisObj = thisObj?thisObj:window
	thisObj.fn = fn
	let result = thisObj.fn(...args)
	delete thisObj.fn
	return result
}

Handwritten Bind code

function myBind(fn,thisObj,...args){
    
    
	return function(...args1){
    
    
		return fn.call(thisObj,...args,...args1)
	}
}

Guess you like

Origin blog.csdn.net/rraxx/article/details/114992596