JavaScript Learning Note 08

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.