Objects
Understanding JavaScript Objects
I am going to clarify some things I said earlier about objects because it is such an important concept in JavaScript. Objects are created from functions inside of JavaScript. Technically, when you create a string variable you are writingvar example = new String(“Welcome”);
This new String()
is a function that creates the string object.
When objects are called, they are usually followed by a .
that tells us a property or a method is about to be called. Let’s hope this analogy works. Think of yourself as an object called you
.
Properties
Now, you have properties about yourself. So, if I typed you.hairColor
, I would expect the results to be whatever hair color you had. That is an object property in a nutshell.
Example
var example = "Welcome"; document.write(example.length);
Result
7
7
The variable example
is a string, and one of its main properties is length
. We get 7 because “Welcome” has 7 characters.
Methods
Methods are actions of or on the object. Again, using you
as an object, you.standUp()
would make you stand up.
Example
var example = "Welcome"; document.write(example.strike());
Result
Welcome
Welcome
The strike()
method simply puts a line through the object string. Notice how the methods have ()
after them. Sometimes, they require arguments, similar to functions.
Example
var example = "Welcome"; document.write(example.charAt(3));
Result
c
c
The method charAt
has an argument of 3, which is why it is shown as charAt(3)
. It returns “c” because “c” is the 4th character. Most methods start from 0. So, charAt(0)
would return “W”.
Referencing JavaScript Objects
JavaScript supports Object-Oriented Programming. It follows a concept of Inheritance, which means that anything created by an object takes on its properties and methods. For example, if you create a string, it inherits properties already preset by the string object.
JavaScript can reference an object in a few ways, but we will only discuss the main ones.
Example
Result
Changed Text
Changed Text
In the above example, we invoke the document.getElementById()
method. This method takes one argument, “example,” which grabs the div object with the id of “example.” Then, we use the property innerHTML
to set its value to “Changed Text.”
Another Example
<html>
<body>
<div data-name="example2"></div>
<script type="text/javascript">
document.getElementsByName("example2")[0].innerHTML="Changed Text";
</script>
</body>
</html>