Java Reference
In-Depth Information
Just as you should always have parentheses after a method, you should never have parentheses after a
property; otherwise, JavaScript thinks you are trying to use a method of that object:
var myString = “Hello, World!”;
alert(myString.length());
The second line adds parentheses after the length property, making JavaScript think it is a method.
This code should have been written like the following code:
var myString = new String(“Hello”);
alert(myString.length);
To compound the issue, it's common for a function to be passed as a parameter to another function (or a
property as you'll see in Chapter 6 when working with events). In these situations, you pass the function
without the opening and closing parentheses () at the end of the function name. Take a look at the
following code:
function foo()
{
alert(“I'm in foo()!”).
}
function bar(fpToCall)
{
alert(“Calling passed function”).
fpToCall();
}
bar(foo);
This code defi nes two functions: foo() and bar(). The foo() function simply displays a message
box telling the user the foo() function is currently executing. The second function, bar(), accepts
one argument that is a function. It displays a message saying it's calling the passed function, and then it
executes that function. The fi nal line calls the bar() function and passes a pointer of the foo() function.
A pointer is a reference to a location in memory (we'll discuss memory references in the next chapter).
As a rule of thumb, use parentheses at the end of the function name when you want to execute the
function, and leave the parentheses off when passing the function to another function or property.
Missing Plus Signs During Concatenation
In the following code, there's a deliberate concatenation mistake:
var myName = “Jeremy”;
var myString = “Hello”;
var myOtherString = “World”;
myString = myName + “ said “ + myString + “ “ myOtherString;
alert(myString);
There should be a + operator between “ “ and myOtherString in the fourth line of code.
Search WWH ::




Custom Search