Java Reference
In-Depth Information
created; it simply creates them. This free property creation might sound great (and it is!), but it does
have drawbacks. The primary issue is that JavaScript won't tell you if you accidentally misspell a
property name; it'll just create a new property with the misspelled name, something that can make it
difficult to track bugs. So always be careful when creating properties.
You can assign methods in the same way, except you assign a function instead of another type of
value, like this:
johnDoe.greet = function() {
alert("My name is " + this.firstName + " " + this.lastName;
};
This code creates a method called greet() , which simply alerts a greeting. A few important things
are important to note in this code.
First, notice there is no name between function and () . A function that has no name is called
an anonymous function . Anonymous functions, in and of themselves, are a syntax error unless
you assign that function to a variable. Once you assign an anonymous function to a variable, that
function's name becomes the name of the variable. So you can execute the anonymous function
assigned to johnDoe.greet like this:
johnDoe.greet();
Next, notice the use of this inside of the function: this.firstName and this.lastName . In
JavaScript, this is a special variable that refers to the current object—the johnDoe object in this
case. It literally means “this object.” So you could rewrite greet() like the following:
johnDoe.greet = function() {
alert("My name is " + johnDoe.firstName + " " + johnDoe.lastName;
};
However, you won't always have the name of object to use in place of this . Therefore, it is preferred
to refer to the current object inside of a method by using this rather than the actual name of the
object.
The full code for creating this johnDoe object looks like this:
var johnDoe = {};
 
johnDoe.firstName = "John";
johnDoe.lastName = "Doe";
johnDoe.greet = function() {
alert("My name is " + johnDoe.firstName + " " + johnDoe.lastName;
};
This is perfectly valid JavaScript, but it takes four statements to create the complete object. These
four statements can be reduced to one statement by defining the entire object using literal notation.
Admittedly, it will look a little weird at first, but you'll soon get used to it:
var johnDoe = {
firstName : "John",
lastName : "Doe",
Search WWH ::




Custom Search