Javascript: functions used as methods

Source: Internet
Author: User

MethodIt is only a JavaScript function that is stored in an object property and called through the object.

<Body> <SCRIPT> var o ={}; O. square = function (x) {return x * x ;}; </SCRIPT> <a href = "javascript: Alert (O. square (2); "> function as a method </a> </body>

That is to say, if there is a function f and an object o, you can use the following code to define a method named M: O. M = f; after defining the M () method of the object o, you can call it like this: O. M (); or If M () expects two parameters, you can call it like this: O. M (x, x + 2 );

Methods have a very important feature:In the method body, the object used to call the method becomes the value of the keyword "this ".. Therefore, when calling O. M (), the method body can use this to reference the object o. The following is a specific example:

Generally, a method executes an operation on an object. Therefore, the method call syntax is a very elegant method that indicates the fact that a function is run on an object. Compare the following two lines of code:

rect.setSize(width,height);setRectSize(rect,width,heigth);

The first line of code is obviously more readable than the second line of code.

When a function is called as a function rather than a method, this keyword references a global object.. The following code can be used as an example:

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.