HTML and CSS Reference
In-Depth Information
Basic objects
JavaScript has been designed as a simple object-based system. An
object
is a data structure that contains
properties
. These properties can be variables, functions, or other objects. When a function is assigned to a
property, it is known as an object's
method
. Objects are predefined in the browser, or you can create your
own. For example, to create an empty object and store it in a variable to reference later, you write:
var objA = {};
This creates an object with no properties and stores it in the variable
objA
. Because JavaScript objects
can be modified by default at any time, we can add a new property to it like this:
objA.name = "My Object A";
This creates a new property called
name
on the
objA
object and assigns it a string value
"My Object A"
.
You can always access the object's property value using the notation
objA.name
. You can also create
properties when declaring a new object, as follows:
var objB = {
name: "My Object B",
hello: function (person) {
console.log("Hello, " + person);
}
};
Here, we've created a new object,
objB
, that contains two properties: the property
name
, which contains a string,
and the property
hello
, within which we've stored a function. Because a function is also an object in JavaScript,
you can pass it around and assign it to variables like any other value. This example method takes a string as an
argument and prints a message to the browser's debugging console:
objB.hello("Gentle Reader"); //prints: "Hello, Gentle Reader"
Creating new kinds of objects
We've declared objects with properties as we've needed them, but what if you want to create multiple objects with the
same property definitions? You can create them one by one, but it's more efficient to use a
constructor
function. A
constructor is a special kind of function that creates a new object based on the properties assigned to that constructor.
After it's set up, you can create a new object instance by invoking the constructor with the
new
command. To distinguish a
constructor function from a regular function, use the convention of starting the name with a capital letter:
function MyObject (person) {
this.name = person;
this.say = function () {
console.log("It's " + this.name);
};
}
var objA = new MyObject("Gentle Reader");
objA.say(); //prints: "It's Gentle Reader"