Each function contains two properties: length and prototype
length: The number of named parameters that the current function wants to accept
prototype: is the real way to preserve all their strength
The code copy is as follows:
function saysName(name) {
alert(name);
}
function sum(num1, num2) {
return num1 + num2;
}
function saysHi() {
alert("hi");
}
alert(sayName.length);//1 Number of parameters
alert(sum.length);//2 Number of parameters: 2
alert(sayHi.length);//0 No parameters
Each function contains two non-inherited methods: apply() and call()
Both methods call functions in a specific scope, which is actually equal to setting the value of this object in the function body
First apply() accepts two parameters: one is the scope of the function running, and the other is the array of parameters (can be an array instance or an argument object)
The code copy is as follows:
function sum(num1, num2) {
return num1 + num2;
}
function callSum1(num1, num2) {
return sum.apply(this, arguments);//Pass in arguments object
}
function callSum2(num1, num2) {
return sum.apply(this, [num1, num2]);
}
alert(callSum1(10, 10));//20
alert(callSum2(10, 20));//30
Secondly, the first parameter of the call method has not changed. What changes is that the other parameters are passed parameters, and the parameters passed to the function need to be listed one by one.
The code copy is as follows:
function sum(num1, num2) {
return num1 + num2;
}
function callSum(num1, num2) {
return sum.call(this, num1, num2);
}
alert(callSum(10, 200));
As for which method is more convenient, it depends entirely on your wishes. If there are no parameters, it will be the same as using either.
However, the appearance of apply and call methods is definitely not just for how to remove the hull parameters.
Their real use lies in the scope on which the extension functions depend.
The code copy is as follows:
window.color = "red";
var o = {color: "blue"};
function saysColor() {
alert(this.color);
}
sayColor();//red
sayColor.call(this);//red
sayColor.call(window);//red
sayColor.call(o);//blue
The biggest advantage of using apply and call to expand scope is that there is no need to have any coupling relationship with the method.
ECMAScript5 also defines a method: bind(). This method creates an instance of a function whose value will be bound to the value passed to the bind function
The code copy is as follows:
window.color = "red";
var o = {color: "blue"};
function saysColor() {
alert(this.color);
}
var bindFun = sayColor.bind(o);
bindFun();//blue
The above is all about this article, I hope you can like it.