Java Reference
In-Depth Information
using a method as a property and vice versa
Another common error is where either you forget to put parentheses after a method with no
parameters, or you use a property and do put parentheses after it.
When calling a method, you must always have parentheses following its name; otherwise, JavaScript
thinks that it must be a pointer to the method or a property. For example, examine the following code:
var nowDate = new Date();
alert(nowDate.getMonth);
The first line creates a Date object, and the second line uses its getMonth property. But you know
that Date objects do not have a getMonth property; it's supposed to be a method. Now, this is
valid JavaScript because you can pass a function pointer—which is what nowDate.getMonth is—to
another function, and as such, the browser will not have any issues executing this code. And in
many cases, you want to do that (like when registering event listeners). But chances are very good
that we intended to call getMonth() . Therefore, the following is the corrected code:
var nowDate = new Date();
alert(nowDate.getMonth());
Note To perhaps confuse the issue: technically, JavaScript doesn't have
methods. What we think of as methods are actually functions assigned to an
object's properties. But it's generally accepted to use the term method to
describe such properties.
Similarly, another common mistake is to type parentheses after a property, making JavaScript think
that you are trying to use a method of that object:
var myString = "Hello, World!";
alert(myString.length());
The second line uses the length property as a method, and JavaScript will attempt to treat it as one.
When this code executes, you will see an error because length cannot be called as a method. This
code should have been written like this:
var myString = new String("Hello");
alert(myString.length);
missing plus signs during Concatenation
Ordinarily, string concatenation is a straightforward process, but it can become confusing when
working with many variables and values. For example, there's a deliberate concatenation mistake in
the following code. Spot it:
var myName = "Jeremy";
var myString = "Hello";
 
Search WWH ::




Custom Search