-
Notifications
You must be signed in to change notification settings - Fork 13
5 Objects
All of the the following JavaScript should be run and tested in the console of your Chrome browser. If you open Google Chrome and press "cmd + option + j" (on Mac OS) to open up your console. You can execute JavaScript right there. You will want to run and test all of your JavaScript in your browser and then copy and save it to an external file to submit to GitHub.
In JavaScript almost everything is an object. Even primitive datatypes (except null and undefined) can be treated as objects.
- Booleans can be objects or primitive data treated as objects
- Numbers can be objects or primitive data treated as objects
- Strings are also objects or primitive data treated as objects
- Dates are always objects
- Maths and Regular Expressions are always objects
- Arrays are always objects
- Even functions are always objects
Objects are a data type that let us store a collection of properties and methods. For now, just think of JavaScript objects as a Ruby hash.
var objectName = {
propertyName: propertyValue,
propertyName: propertyValue,
...
};
var aboutMe = {
hometown: "Pasadena, CA",
hair: "brown"
};
var lizzieTheCat = {
age: 18,
furColor: "grey",
likes: ["catnip", "milk"],
birthday: {"month": 7, "day": 17, year: 1994}
};
Access properties using "dot notation":
var aboutMe = {
hometown: "Pasadena, CA",
hair: "brown"
};
var myHometown = aboutMe.hometown; // "Pasadena, CA"
Or using "bracket notation" (like arrays):
var myHair = aboutMe["hair"]; // "brown"
// Non-existent properties will return undefined:
var myGender = aboutMe["gender"]; // undefined
Use dot or bracket notation with the assignment operator to change objects. Below is an example of how we would change existing properties:
var aboutMe = {
hometown: "Pasadena, CA",
hair: "brown"
};
aboutMe.hair = "blue";
// Or add new properties:
aboutMe.gender = "female";
// You can also delete properties:
delete aboutMe.gender;
Since arrays can hold any data type, they can also hold objects:
var myCats = [
{name: "Lizzie",
age: 18},
{name: "Daemon",
age: 1}
];
for (var i = 0; i < myCats.length; i++) {
var myCat = myCats[i];
console.log(myCat.name + ' is ' + myCat.age + ' years old.');
}
Just like other data types, objects can be passed into functions:
var lizzieTheCat = {
age: 18,
furColor: "grey",
likes: ["catnip", "milk"],
birthday: {"month": 7, "day": 17, year: 1994}
}
function describeCat(cat) {
console.log("This cat is " + cat.age + " years old with " + cat.furColor + " fur.");
}
describeCat(lizzieTheCat);
Object properties can also be functions. Object functions are called "methods".
var lizzieTheCat = {
age: 18,
furColor: 'grey',
meow: function() {
console.log('meowww');
},
eat: function(food) {
console.log('Yum, I love ' + food);
},
sleep: function(numMinutes) {
for (var i = 0; i < numMinutes; i++) {
console.log('z');
}
}
};
Call object methods using dot notation:
lizzieTheCat.meow(); // meowww
lizzieTheCat.eat('brown mushy stuff'); // Yum, I love brown mushy stuff
lizzieTheCat.sleep(3);
// z
// z
// z
JavaScript is an Object Oriented Programming (OOP) language. A programming language can be called object-oriented if it provides four basic capabilities to developers:
- Encapsulation - the capability to store related information, whether data or methods, together in an object
- Aggregation - the capability to store one object inside of another object
- Inheritance - the capability of a class to rely upon another class (or number of classes) for some of its properties and methods
- Polymorphism - the capability to write one function or method that works in a variety of different ways
Objects are composed of attributes. If an attribute contains a function, it is considered to be a method of the object otherwise, the attribute is considered a property.
Object properties can be any of the three primitive data types, or any of the abstract data types, such as another object. Object properties are usually variables that are used internally in the object's methods, but can also be globally visible variables that are used throughout the page.
The syntax for adding a property to an object is:
objectName.objectProperty = propertyValue;
Following is a simple example to show how to get a document title using "title" property of document object:
var str = document.title;
The methods are functions that let the object do something or let something be done to it. There is little difference between a function and a method, except that a function is a standalone unit of statements and a method is attached to an object and can be referenced by the this keyword.
Methods are useful for everything from displaying the contents of the object to the screen to performing complex mathematical operations on a group of local properties and parameters.
Following is a simple example to show how to use write() method of document object to write any content on the document:
document.write("This is test");
When using this inside of an object, it will refer to the parent object.
var Contact = {
firstName: "Bitmaker",
lastName: "Labs",
email: "contact@bitmakerlabs.com",
display: function () { return this.firstName + " " + this.lastName + " email is: " + this.email; }
};
Contact.display(); // "Bitmaker Labs email is: contact@bitmakerlabs.com"
We will also talk about "this" in the context of jQuery as well.
For a more detailed explanation, feel free to check out the MDN explanation of this
OR
This blog article called Understanding the "this" in JavaScript
All user-defined objects and built-in objects are descendants of an object called Object.
The new operator is used to create an instance of an object. To create an object, the new operator is followed by the constructor method.
In the following example, the constructor methods are Object(), Array(), and Date(). These constructors are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
A constructor is a function that creates and initializes an object. JavaScript provides a special constructor function called Object() to build the object. The return value of the Object() constructor is assigned to a variable.
The variable contains a reference to the new object. The properties assigned to the object are not variables and are not defined with the var keyword.
This example demonstrates how to create an object:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>
This example demonstrates how to create an object with a User-Defined Function. Here this keyword is used to refer to the object that has been passed to a function:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
this.author = author;
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>
The previous examples demonstrate how the constructor creates the object and assigns properties. But we need to complete the definition of an object by assigning methods to it.
Here is a simple example to show how to add a function along with an object:
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
function addPrice(amount){
this.price = amount;
}
function book(title, author){
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script>
</body>
</html>