JavaScript Working with Objects
Learn how to create and use objects in JavaScript.
1. Creating Objects
Objects are collections of key-value pairs. You can create them using object literals.
JavaScript Code
Live JavaScript representation with highlighted changes
const myCar = {make: "Ford",model: "Mustang",year: 1969};console.log(myCar.make);
2. Defining Methods
A method is a function associated with an object. It's a property of an object that is a function.
JavaScript Code
Live JavaScript representation with highlighted changes
const myObj = {myMethod: function(params) {console.log("Hello from myMethod!");}};myObj.myMethod();
3. Using `this`
The this
keyword refers to the object the method is called on.
JavaScript Code
Live JavaScript representation with highlighted changes
const person = {name: "John",sayHi: function() {console.log("Hi, I'm " + this.name);}};person.sayHi();
Console Output