Section 8.4. Functions as Methods


8.4. Functions as Methods

A method is nothing more than a JavaScript function that is stored in a property of an object and invoked through that object. Recall that functions are data values and that there is nothing special about the names with which they are defined; a function can be assigned to any variable, or even to any property of an object. If you have a function f and an object o, you can define a method named m with the following line:

 o.m = f; 

Having defined the method m() of the object o, invoke it like this:

 o.m(); 

Or, if m() expects two arguments, you can invoke it like this:

 o.m(x, x+2); 

Methods have one very important property: the object through which a method is invoked becomes the value of the this keyword within the body of the method. Thus, when you invoke o.m(), the body of the method can refer to the object o with the this keyword. Here is a concrete example:

 var calculator = {  // An object literal     operand1: 1,     operand2: 1,     compute: function() {         this.result = this.operand1 + this.operand2;     } }; calculator.compute();       // What is 1+1? print(calculator.result);   // Display the result 

The this keyword is important. Any function that is used as a method is effectively passed an implicit argumentthe object through which it is invoked. Typically, a method performs some sort of operation on that object, so the method-invocation syntax is a particularly elegant way to express the fact that a function is operating on an object. Compare the following two lines of code:

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

The hypothetical functions invoked in these two lines of code may perform exactly the same operation on the (hypothetical) object rect, but the method-invocation syntax in the first line more clearly indicates the idea that it is the object rect that is the primary focus of the operation. (If the first line does not seem a more natural syntax to you, you are probably new to object-oriented programming.)

When a function is invoked as a function rather that as a method, the this keyword refers to the global object. Confusingly, this is true even when a nested function is invoked (as a function) within a containing method that was invoked as a method: the this keyword has one value in the containing function but (counterintuitively) refers to the global object within the body of the nested function.

Note that this is a keyword, not a variable or property name. JavaScript syntax does not allow you to assign a value to this.




JavaScript. The Definitive Guide
JavaScript: The Definitive Guide
ISBN: 0596101996
EAN: 2147483647
Year: 2004
Pages: 767

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net