Task5

PHOTO EMBED

Fri Nov 01 2024 19:47:59 GMT+0000 (Coordinated Universal Time)

Saved by @wt

TASK 05

// Prototypal inheritance
function Person(name) {
    this.name = name;
}

Person.prototype.greet = function () {
    console.log(Hello, my name is ${this.name}.);
};

function Employee(name, jobTitle) {
    Person.call(this, name); // Call parent constructor
    this.jobTitle = jobTitle;
}

Employee.prototype = Object.create(Person.prototype);
Employee.prototype.constructor = Employee;
Employee.prototype.describeJob = function () {
    console.log(I am a ${this.jobTitle}.);
};

// Closure example
function createCounter() {
    let count = 0; // Private variable
    return () => ++count; // Increment count and return
}

// Callback example
function fetchData(callback) {
    setTimeout(() => {
        const data = { id: 1, name: "John Doe" };
        callback(data);
    }, 1000); // Simulate async operation
}

// Promise example
function fetchDataPromise() {
    return new Promise((resolve) => {
        setTimeout(() => {
            resolve({ id: 2, name: "Jane Smith" });
        }, 1000);
    });
}

// Async/Await example
async function fetchAndProcessData() {
    const data = await fetchDataPromise();
    console.log(Fetched data: ${JSON.stringify(data)});
}

// Instantiate and use
const person = new Person("Alice");
const employee = new Employee("Bob", "Developer");

person.greet(); // Hello, my name is Alice.
employee.greet(); // Hello, my name is Bob.
employee.describeJob(); // I am a Developer.

const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2

fetchData((data) => {
    console.log(Fetched data using callback: ${JSON.stringify(data)});
});

fetchAndProcessData(); // Fetched data: {"id":2,"name":"Jane Smith"}
content_copyCOPY