Methods
A
method is nothing more than a JavaScript
function that is invoked through an 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 we have a function
f
and an object o
, we can
define a method named m
with the following line:
o.m = f;
Having defined the method m( )
of the object
o
, we invoke it like this:
o.m( );
Or, if m( )
expects two arguments, we might 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. For example, when we invoke
o.m( )
, the body of the method can refer to the
object o
with the this
keyword.
The discussion of the this
keyword should begin to
clarify why we use methods at all. Any function that is used as a
method is effectively passed an extra argument -- the 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);
These two lines may perform exactly the same operation on the object
rect
, but the method invocation syntax in the first line more clearly indicates the idea that it is the object ...
Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.