Each function contains two properties: Length and prototype
Length: The number of named arguments that the current function expects to accept
Prototype: The real way to preserve all their power
Copy Code code as follows:
function Sayname (name) {
alert (name);
}
function sum (NUM1, num2) {
return NUM1 + num2;
}
function Sayhi () {
Alert ("HI");
}
alert (sayname.length);//1 Number of arguments one
alert (sum.length);//2 parameter number: 2
alert (sayhi.length);//0 no parameters
Each function contains two methods that are not inherited: Apply () and call ()
Both of these methods call a function in a specific scope and are actually equal to the value of the This object in the function body
Apply () First accepts two parameters: one is the scope of the function run, the other is an array of parameters (can be an array instance or a arguments object)
Copy Code code as follows:
function sum (NUM1, num2) {
return NUM1 + num2;
}
function CallSum1 (NUM1, num2) {
Return sum.apply (this, arguments);//Incoming 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 does not change, the change is that the remaining parameters are passed parameters, the parameters passed to the function need to be enumerated individually
Copy Code code as follows:
function sum (NUM1, num2) {
return NUM1 + num2;
}
function Callsum (NUM1, num2) {
Return Sum.call (this, NUM1, num2);
}
Alert (Callsum (10, 200));
It is entirely up to you to decide which method is more convenient to use. If there are no parameters, use whichever is the same.
However, the apply and call methods appear to be absolutely not just about how to get to the hull parameters.
Their real purpose is to expand the scope on which the function is run.
Copy Code code as follows:
Window.color = "Red";
var o = {color: "Blue"};
function Saycolor () {
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 extend a scope is that there is no coupling between the methods.
ECMAScript5 also defines a method: Bind (). This method creates an instance of the function whose this value is bound to the value passed to the BIND function
Copy Code code as follows:
Window.color = "Red";
var o = {color: "Blue"};
function Saycolor () {
alert (This.color);
}
var bindfun = Saycolor.bind (o);
Bindfun ();//blue
The above is the entire content of this article, I hope that small partners can enjoy.