Join Regular Classroom : Visit ClassroomTech

JavaScript – codewindow.in

Related Topics

HTML

Introduction
Html page 1
Html page 2
Html page3
Html page4

HTML Elements and structure
Html page 5
Html page 6
Html page 7

HTML Headings and Paragraphs
Html page 8
Html page 9
Html page 10

HTML Lists and Tables
Html page 11
Html page 12
Html page 13

HTML Forms and Input Fields
Html page 14
Html page 15
Html page 16

HTML Images and Media
Html page 17
Html page 18

HTML Links and Anchors
Html page 19
Html page 20
Html page 21

HTML Styles and Formatting
Html page 22

HTML Semantic Elements
Html page 23
Html page 24

HTML Attributes
Html page 25
Html page 26

HTML JavaScript Integration
Html page 27
Html page 28
Html page 29
Html page 30

HTML Document and Browser Support
Html page 31
Html page 32

HTML5 New Elements and Attributes
Html page 33
Html page 34
Html page 35
Html page 36

HTML Accessibility and Web Standards
Html page 37
Html page 38
Html page 39

HTML Responsive Design and Mobile Devices.
Html page 40
Html page 41
Html page 42

JAVASCRIPT

const Singleton = (function() {
  let instance;

  function createInstance() {
    // Create the single instance
    return { /* ... */ };
  }

  return {
    getInstance: function() {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

const singletonInstance1 = Singleton.getInstance();
const singletonInstance2 = Singleton.getInstance();

console.log(singletonInstance1 === singletonInstance2); // Output: true
  1. Factory Pattern: The Factory pattern is a creational pattern that provides an interface for creating objects but allows subclasses to alter the type of objects that will be created. It is useful when you want to create different instances of objects without exposing the creation logic.
class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
}

class ProductFactory {
  createProduct(name, price) {
    return new Product(name, price);
  }
}

const factory = new ProductFactory();
const product1 = factory.createProduct('Phone', 500);
const product2 = factory.createProduct('Laptop', 1000);
  1. Observer Pattern: The Observer pattern allows an object (subject) to notify a list of dependents (observers) when its state changes. It’s commonly used in event handling and can help achieve decoupling between different components.
class Subject {
  constructor() {
    this.observers = [];
  }

  addObserver(observer) {
    this.observers.push(observer);
  }

  removeObserver(observer) {
    this.observers = this.observers.filter((obs) => obs !== observer);
  }

  notifyObservers(data) {
    this.observers.forEach((observer) => observer.update(data));
  }
}

class Observer {
  update(data) {
    // Handle the updated data
    console.log('Received data:', data);
  }
}

const subject = new Subject();
const observer1 = new Observer();
const observer2 = new Observer();

subject.addObserver(observer1);
subject.addObserver(observer2);

subject.notifyObservers('Hello, observers!'); // Output: "Received data: Hello, observers!"
4. Module Pattern: The Module pattern is a way to create encapsulated and private components in JavaScript. It uses closures to provide public interfaces while keeping the internal state and functions private.
const CounterModule = (function() {
  let count = 0;

  function increment() {
    count++;
  }

  function decrement() {
    count--;
  }

  function getCount() {
    return count;
  }

  return {
    increment,
    decrement,
    getCount
  };
})();

CounterModule.increment();
CounterModule.increment();
console.log(CounterModule.getCount()); // Output: 2
  1. MVC Pattern: The Model-View-Controller (MVC) pattern is an architectural pattern that separates an application into three interconnected components: Model (data and business logic), View (presentation and user interface), and Controller (handles user input and updates the model and view). MVC promotes separation of concerns and maintainability.
These are just a few examples of common design patterns in JavaScript. There are many more patterns, each serving different purposes and addressing specific challenges. Understanding design patterns can help you write more maintainable, modular, and scalable code.
class EventEmitter {
  constructor() {
    this.events = {};
  }

  on(eventName, callback) {
    if (!this.events[eventName]) {
      this.events[eventName] = [];
    }
    this.events[eventName].push(callback);
  }

  emit(eventName, data) {
    const eventCallbacks = this.events[eventName];
    if (eventCallbacks) {
      eventCallbacks.forEach((callback) => callback(data));
    }
  }
}
2. Create Event Subscribers: Next, you can create various components or modules (subscribers) that are interested in specific events. These components will register themselves with the event emitter by subscribing to events they want to be notified of.
const eventEmitter = new EventEmitter();

// Subscriber 1
eventEmitter.on('userLoggedIn', (user) => {
  console.log(`User ${user.name} logged in.`);
});

// Subscriber 2
eventEmitter.on('userLoggedOut', (user) => {
  console.log(`User ${user.name} logged out.`);
});
3. Trigger Events: Now you can trigger events in different parts of your application when appropriate actions occur. For example, when a user logs in or logs out, you can emit the corresponding events, and the subscribed components will react accordingly.
// Somewhere in the code when a user logs in
const loggedInUser = { name: 'John' };
eventEmitter.emit('userLoggedIn', loggedInUser);

// Somewhere in the code when a user logs out
const loggedOutUser = { name: 'Alice' };
eventEmitter.emit('userLoggedOut', loggedOutUser);
  1. Benefit from Decoupling: With this event-driven architecture, the components don’t need to know each other directly. They only need to interact with the central event emitter. This promotes decoupling between different parts of the application, making it easier to maintain and extend.
Event-driven architecture is commonly used in modern JavaScript frameworks and libraries, such as Node.js, React, and Vue.js, to facilitate communication and coordination between different components. By using this pattern, you can build more modular, flexible, and scalable applications.
// worker.js
self.onmessage = function(event) {
  const data = event.data;
  const result = processData(data);
  self.postMessage(result);
};

function processData(data) {
  // Perform time-consuming computations or I/O operations here
  // Return the result to be sent back to the main thread
  return data * 2;
}
2. Creating and Using the Web Worker in the Main Thread: In the main thread (typically, your main JavaScript file), you can create an instance of the Web Worker and handle communication with it using onmessage and postMessage.
// main.js
const worker = new Worker('worker.js');

worker.onmessage = function(event) {
  const result = event.data;
  console.log(`Result received: ${result}`);
};

const dataToSend = 10;
worker.postMessage(dataToSend);
In this example, the main thread creates a Web Worker instance using the “worker.js” file. The onmessage event listener listens for messages sent from the worker using self.postMessage(), and when the worker sends a message, the main thread handles it and logs the result.
  1. Terminate the Web Worker: Web Workers continue to run indefinitely unless terminated. To terminate a worker, you can call the worker.terminate() method.
// Terminate the Web Worker after processing is done
worker.terminate();
Web Workers can significantly improve the responsiveness of web applications by offloading intensive tasks to background threads, leaving the main thread available for handling user interactions. They are commonly used for tasks like data processing, image manipulation, encryption, and other CPU-intensive operations.
However, it’s important to note that Web Workers have some limitations. They run in a separate context and cannot directly access the DOM or interact with the main thread’s variables. Communication between the main thread and the Web Worker is achieved using serialization and deserialization of messages through the postMessage() and onmessage mechanisms.

      

Popular Category

Topics for You

HTML

Introduction
Html page 1
Html page 2
Html page3
Html page4

HTML Elements and structure
Html page 5
Html page 6
Html page 7

HTML Headings and Paragraphs
Html page 8
Html page 9
Html page 10

HTML Lists and Tables
Html page 11
Html page 12
Html page 13

HTML Forms and Input Fields
Html page 14
Html page 15
Html page 16

HTML Images and Media
Html page 17
Html page 18

HTML Links and Anchors
Html page 19
Html page 20
Html page 21

HTML Styles and Formatting
Html page 22

HTML Semantic Elements
Html page 23
Html page 24

HTML Attributes
Html page 25
Html page 26

HTML JavaScript Integration
Html page 27
Html page 28
Html page 29
Html page 30

HTML Document and Browser Support
Html page 31
Html page 32

HTML5 New Elements and Attributes
Html page 33
Html page 34
Html page 35
Html page 36

HTML Accessibility and Web Standards
Html page 37
Html page 38
Html page 39

HTML Responsive Design and Mobile Devices.
Html page 40
Html page 41
Html page 42

Go through our study material. Your Job is awaiting.

Recent Posts
Categories