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: