JavaScript changes this to point to apply, call and bind methods

apply method

The apply method is used to change the pointing of this

The usage syntax of apply:

Function name.apply (object, [parameter 1, parameter 2,...]);
method name.apply (object, [parameter 1, parameter 2,...]); The
apply method is to pass parameters in an array

// 获取按钮
		var btn=document.querySelectorAll(".btn");
		// 使用apply方法,改变Array中forEach方法的指向,循环遍历解析按钮注册点击事件
		Array.prototype.forEach.apply(btn,[function (ele) {
    
    
			addEventListener(ele,"click",clickHandle);
		}]);
		
		//定义一个函数
		function fn(x,y) {
    
    
				console.log("我是window对象的方法:"+(x+y)+this.sex);
			}
			
			window.fn(50,60);
			
			//创建一个对象
			var obj={
    
    
				age:10,
				sex:"男"
			};
			
			window.fn.apply(obj,[10,20]);//30男

Whether it is a system constructor method or a self-defined function method, you can use the apply method to change the direction of this

call method

The usage syntax of call:

Function name. call (object, parameter 1, parameter 2, ...);
method name. call (object, parameter 1, parameter 2, ...);
The call method is to pass parameters in string form

// 获取所有的点赞标签
var praise=document.querySelectorAll(".praise");
// 使用call方法,改变Array中forEach方法的指向,遍历点赞标签,注册点击事件
Array.prototype.forEach.call(praise,(function (ele) {
    
    
	addEventListener(ele,"click",praHandle);
}));

function fn(x,y) {
    
    
				console.log("我是window对象的方法:"+(x+y)+this.sex);
			}
			
			window.fn(50,60);
			
			//创建一个对象
			var obj={
    
    
				age:10,
				sex:"男"
			};
			
			window.fn.call(obj,10,50);//60男

Whether it is a system constructor method or a self-defined function method, you can change the direction of this through the call method

bind method

The bind method means copying. The parameter can be passed in when copying, or it can be passed in when calling after copying.
apply and call change this to point to
the bind method when calling, and change this when assigning a value pointing to

			// 人的构造函数
			function Person(age) {
    
    
				this.age=age;
			}
			// 添加原型方法
			Person.prototype.play=function () {
    
    
				console.log(this+"====>"+this.age);
			};
			// 学生的构造函数
			function Student(age) {
    
    
				this.age=age;
			}
			
			//实例化对象
			var per=new Person(60);
			var stu=new Student(80);
			
			//通过bind方法赋值一份
			var ff=per.play.bind(stu);
			ff();
  • bind is used to make a copy

Syntax used:

Function name.bind(object, parameter 1, parameter 2,…);---->The return value is the name of the function method after copying.bind
(object, parameter 1, parameter 2,…);----> The return value is this method after copying

Guess you like

Origin blog.csdn.net/weixin_45576567/article/details/102710622