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"}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter