Length,call and apply
<script type= "Text/javascript" >
function fn1 () {
}
function Fn2 (num1,num2) {
}
function Fn3 (NUM1) {
}
The length of the function indicates the value of the parameter expected by the function
alert (fn1.length);//0
alert (fn2.length);//2
alert (fn3.length);//1
</script>
<script type= "Text/javascript" >
function sum (num1,num2) {
return num1+num2;
}
function CallSum1 (num1,num2) {
Use the SUM function to complete a call, and the parameter of the call is the parameter of the CALLSUM1 function.
The second argument to apply represents a set of parameter arrays
Return sum.apply (this,arguments);
}
function callSum2 (num1,num2) {
The key is that the second argument is an array
Return sum.apply (this,[num1,num2]);
}
Alert (CALLSUM1 (12,22));
Alert (callSum2 (22,32));
function callSum3 (num1,num2) {
Call is passed through the parameter list, and the other is not any different from apply.
Return Sum.call (THIS,NUM1,NUM2);
}
Alert (CALLSUM3 (22,33));
</script>
</body>
<script type= "Text/javascript" >
/**
* When you need to create a class, the properties and methods of the set class need to be referenced by the This keyword
* However, it is important to note that the This keyword will be different depending on the calling object when it is called
*/
var color = "Red";
function Showcolor () {
alert (This.color);
}
/**
* created a class with a color attribute and a Show method
*/
function Circle (color) {
This.color = color;
}
var c = new Circle ("Yellow");
Showcolor.call (this);//use context to invoke Showcolor, the result is red
Showcolor.call (c);//The context object is C, and the result is yellow
/**
* After using call and apply, you will not need to define a method in the object.
* This is a use of call and apply
*/
</script>
JavaScript Learning Note 08