Java Reference
In-Depth Information
Calling an Object's Methods
Methods are very much like functions in that they can be used to perform useful tasks, such as
getting the hours from a particular date or generating a random number. Again like functions, some
methods return a value, such as a Date object's getHours() method, whereas others perform a task,
but return no data, such as an Array object's sort() method.
Using the methods of an object is very similar to using properties, in that you put the object's
variable name first, then a dot, and then the name of the method. For example, to sort the elements
of an Array in the variable myArray , you can use the following code:
myArray.sort();
Just as with functions, you can pass parameters to some methods by placing the parameters between
the parentheses following the method's name. However, whether or not a method takes parameters,
you must still put parentheses after the method's name, just as you did with functions. As a general
rule, anywhere you can use a function, you can use a method of an object.
primitives and objects
You should now have a good idea about the difference between primitive data, such as numbers and
strings, and object data, such as Date s and Array is However, as was mentioned earlier, there is also
a String object. Where does this fit in?
In fact, there are String , Number , and Boolean objects corresponding to the string, number,
and boolean primitive data types. For example, to create a String object containing the text
"I'm a String object" you can use the following code:
var myString = new String("I'm a String object");
String objects have the length property just as Array objects do. This returns the number of
characters in the String object. For example,
var lengthOfString = myString.length;
would store the value 19 in the variable lengthOfString (remember that spaces are referred to as
characters, too).
But what if you had declared a primitive string called mySecondString holding the text
"I'm a primitive string" like this:
var mySecondString = "I'm a primitive string";
and wanted to know how many characters could be found in this primitive string?
This is where JavaScript helps you out. Recall from previous chapters that JavaScript can handle
the conversion of one data type to another automatically. For example, if you tried to add a string
primitive to a number primitive, like this:
theResult = "23" + 23;
 
Search WWH ::




Custom Search