JS apply and call methods

Both of these methods are methods of the function object and need to be called through the function object.
When calling a function, call and apply will both call the function to execute.
In mobilizing call() and apply(), you can specify an object as the first parameter. At this time, this object will become the this when the function is executed (the window pointed to by this when the ordinary function is executed)

function fun(){
    
    
		Alert("我是fun函数");
}

fun.apply();
fun.call();
fun();

The situation of this:
1. Called in the form of a function, this is always window
2. Called in the form of a method, this is the object that calls the method
3. When called in the form of a constructor, this is the newly created object
4. Use When call and apply are called, this is the specified object

var obj = {
    
    
	name:"obj",
	sayName:funcrion(){
    
    
		alert(this.name);
	}

}


fun.call(obj,2,3);
fun.call(obj,[2,3]);

The call() method can pass the actual parameters in turn after the object. The
apply() method needs to encapsulate the actual parameters into an array and pass them uniformly.

Guess you like

Origin blog.csdn.net/sinat_33940108/article/details/111994258