JavaScript uses apply(this, arguments) in the method

First understand the arguments: The
arguments object is a built-in object of JavaScript function, which contains the parameter array of the function call.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>入门JavaScript this</title>
</head>

<h2>JavaScript <b>this</b> arguments</h2>

<p id="demo"></p>
</head>
<body>
<script language="javascript">

function findMax() {
    
    
    var i, max = arguments[0];
    console.log(arguments);
    if(arguments.length < 2) return max;
 
    for (i = 0; i < arguments.length; i++) {
    
    
        if (arguments[i] > max) {
    
    
            max = arguments[i];
        }
    }
    return max;
}
console.log("最大值为:",findMax(1, 123, 500, 115, 44, 88)); 
</script>
</body>
</html>

The output on the console is:
Insert picture description hereand then the use of
apply : The apply() method accepts two parameters: the
first parameter is thisObject, and the thisObject is used to replace the this point in the function body when calling, which is the scope of function operation.
The second parameter is an array of parameters (arguments), the function will replace the "parameter list" with the value of the array.

var A={
    
    
    name:"我是小A",
    fun:function(sex,age){
    
    
        console.log("大家好! "+this.name+" 我是个"+sex+" 今年"+age+"岁")
    }
}

var B = {
    
    
    name:"我是小B"
};
var monies = ["男生",20];
A.fun.apply(B,monies);    

Apply the method of A to object B, and the output in the console is:

大家好! 我是小B 我是个男生 今年20

Now put apply(this, argument) in the method to use:

var A={
    
    
    name:"我是小A",
    funA:function(sex,age){
    
    
        console.log("大家好! "+this.name+" 我是个"+sex+" 今年"+age+"岁")
    }
}

var B = {
    
    
    name:"我是小B",
	funB:function()
	{
    
    
	console.log(this.name,arguments);
	A.funA.apply(B,arguments)
	}
	
};

B.funB("男生",20);


Use the method of A in object B, and use apply to change the point of this. Arguments are the parameters passed in:
Insert picture description here
in the method funB of object B, this represents B, so apply(B,arguments) is equivalent to apply(this, arguments)
so use apply(this, arguments) to easily write methods that apply to different objects.
Looking at the previous code, I saw a usage, the source code is not easy to show, here is an analogy:

var B = {
    
    
    name:"我是小B",
	funB:function()
	{
    
    
	console.log(this.name,arguments);
	B.funB.apply(this,arguments)
	}
};
B.funB("男生",20);

Because of the use of recursion, this will cause the stack to be full. I don't know why it is used this way. I hope the big guys passing by can explain it. . . .
Insert picture description here

Guess you like

Origin blog.csdn.net/liulanba/article/details/112981865