Declaring and defining objects in js

PHOTO EMBED

Fri Nov 15 2024 13:18:09 GMT+0000 (Coordinated Universal Time)

Saved by @login123

const person = {
    name: "Alice",
    age: 25,
    greet: function() {
        console.log(`Hi, I'm ${this.name}.`);
    }
};
console.log(person.name);
person.greet();

const car = new Object();
car.brand = "Toyota";
car.model = "Corolla";
car.year = 2021;
console.log(car.brand);

function Book(title, author) {
    this.title = title;
    this.author = author;
    this.getInfo = function() {
        return `${this.title} by ${this.author}`;
    };
}
const book1 = new Book("1984", "George Orwell");
console.log(book1.getInfo());

class Animal {
    constructor(type, sound) {
        this.type = type;
        this.sound = sound;
    }
    makeSound() {
        console.log(this.sound);
    }
}

const cat = new Animal("Cat", "Meow");
cat.makeSound();

const student = {
    name: "Bob",
    grade: "A",
    subjects: ["Math", "Science"]
};
console.log(student.subjects[0]);
content_copyCOPY