Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
Learn how to access properties and methods using dot and bracket notation.
Object Literals Referring to Themselves
Many times, when writing methods for objects, you might want to refer to one of that object's properties. For example, consider the following code:
const teacher = {
firstName : "Ashley",
lastName : "Boucher"
}
I may want to add a method to this object literal called printName()
that will log both the first and last name properties of the teacher
variable to the console. To access the value of these properties inside the method, I'll use the this
keyword instead of the variable name. This way, you'll always be able to access the property values attached to that particular object:
const teacher = {
firstName : "Ashley",
lastName : "Boucher",
printName: function(){
console.log(this.firstName + this.lastName);
}
}
Template Literals
We use template literals a lot in this course. They are a feature in ES2015 and make outputting strings much easier. If you're unfamiliar with them, review this workshop from the Treehouse library.
Installing Node on Your Local Machine
If you'd like to download node.js on your local machine, visit the Node.js website, and follow the instructions there. Windows users can also reference this article from Treehouse's blog.
JSON and Bracket Notation
JSON, short for JavaScript Object Notation, is a data-interchange format. It has a special syntax that looks a lot like the syntax for JavaScript objects. Sometimes, keys in JSON might be more than one word. Take a look at this sample JSON data:
var data = {
"First Name" : "John",
"Last Name" : "Doe"
}
To access the first name or last name properties of this JSON data, you would use bracket notation:
var first = data['First Name'];
var last = data['Last Name'];
You can learn more about JSON here.
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up