closure, callback
Thu Nov 21 2024 18:02:35 GMT+0000 (Coordinated Universal Time)
Saved by
@coding1
// Prototypal Inheritance
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a noise.`);
};
function Dog(name) {
Animal.call(this, name); // Call the parent constructor
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.speak = function() {
console.log(`${this.name} barks.`);
};
// Closure
function createCounter() {
let count = 0; // Private variable
return {
increment: function() {
count++;
return count;
},
decrement: function() {
count--;
return count;
},
getCount: function() {
return count;
}
};
}
// Callback
function fetchData(callback) {
setTimeout(() => {
const data = { message: "Data fetched!" };
callback(data);
}, 1000);
}
// Promise
function fetchDataPromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { message: "Data fetched with Promise!" };
resolve(data);
}, 1000);
});
}
// Async/Await
async function fetchDataAsync() {
const data = await fetchDataPromise();
console.log(data.message);
}
// Demonstration
function demo() {
// Prototypal Inheritance
const dog = new Dog('Buddy');
dog.speak(); // Output: Buddy barks.
// Closure
const counter = createCounter();
console.log(counter.increment()); // Output: 1
console.log(counter.increment()); // Output: 2
console.log(counter.decrement()); // Output: 1
console.log(counter.getCount()); // Output: 1
// Callback
fetchData((data) => {
console.log(data.message); // Output: Data fetched!
});
// Promise
fetchDataPromise().then((data) => {
console.log(data.message); // Output: Data fetched with Promise!
});
// Async/Await
fetchDataAsync(); // Output: Data fetched with Promise!
}
// Run the demonstration
demo();
content_copyCOPY
Comments