This article mainly introduces the javascript function attributes and methods. For more information, see. Each function contains two attributes: length and prototype.
Length: The number of name parameters that the current function wants to accept
Prototype: is the true solution to save all of their strengths
The Code is as follows:
Function sayName (name ){
Alert (name );
}
Function sum (num1, num2 ){
Return num1 + num2;
}
Function sayHi (){
Alert ("hi ");
}
Alert (sayName. length); // One Parameter count
Alert (sum. length); // Two Parameters
Alert (sayHi. length); // 0 No Parameter
Each function contains two non-inherited methods: apply () and call ()
Both methods call functions in a specific scope, which is equivalent to setting the value of this object in the function body.
First, apply () accepts two parameters: one is the function running scope, and the other is the parameter array (it can be an array instance or an arguments object)
The Code is as follows:
Function sum (num1, num2 ){
Return num1 + num2;
}
Function callSum1 (num1, num2 ){
Return sum. apply (this, arguments); // input the arguments object
}
Function callSum2 (num1, num2 ){
Return sum. apply (this, [num1, num2]);
}
Alert (callSum1 (10, 10); // 20
Alert (callSum2 (10, 20); // 30
Second, the first parameter of the call method remains unchanged. The other parameters are passed. parameters passed to the function must be listed one by one.
The Code is as follows:
Function sum (num1, num2 ){
Return num1 + num2;
}
Function callSum (num1, num2 ){
Return sum. call (this, num1, num2 );
}
Alert (calsum (10,200 ));
Which method is more convenient depends on your wishes. If no parameter exists, use the same method.
However, the appearance of the apply and call methods is definitely not just about how to get the hull parameters.
They are used to expand the scope on which the function depends.
The Code is 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 benefit of using apply and call to expand the scope is that there is no need to have any coupling relationship with the method.
ECMAScript5 also defines a method: bind (). This method will create a function instance, and its this value will be bound to the value passed to the bind Function
The Code is as follows:
Window. color = "red ";
Var o = {color: "blue "};
Function sayColor (){
Alert (this. color );
}
Var bindFun = sayColor. bind (o );
BindFun (); // blue
The above is all the content of this article. I hope my friends will like it.