Skip to Content
JavaScript: The Definitive Guide, Fourth Edition
book

JavaScript: The Definitive Guide, Fourth Edition

by David Flanagan
November 2001
Intermediate to advanced
936 pages
68h 43m
English
O'Reilly Media, Inc.
Content preview from JavaScript: The Definitive Guide, Fourth Edition

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

JavaScript: A Beginner's Guide, Fourth Edition, 4th Edition

John Pollock
JavaScript Cookbook, 3rd Edition

JavaScript Cookbook, 3rd Edition

Adam D. Scott, Matthew MacDonald, Shelley Powers

Publisher Resources

ISBN: 0596000480Supplemental ContentCatalog PageErrata