자바스크립트에서 'this' 키워드를 이용한 라우팅 처리 방법

라우팅은 웹 애플리케이션에서 특정 URL에 해당하는 동작을 수행하기 위해 사용되는 중요한 개념입니다. 자바스크립트에서 ‘this’ 키워드를 활용하여 간단하게 라우팅을 처리하는 방법을 소개하겠습니다.

1. 객체 리터럴을 사용한 라우팅 처리

const router = {
  routes: [],
  addRoute(path, callback) {
    this.routes.push({ path, callback });
  },
  navigate(path) {
    const matchedRoute = this.routes.find(route => route.path === path);
    if (matchedRoute) {
      matchedRoute.callback();
    } else {
      console.log("404 - Not Found");
    }
  }
};

router.addRoute("/", () => {
  console.log("Home Page");
});

router.addRoute("/about", () => {
  console.log("About Page");
});

router.addRoute("/contact", () => {
  console.log("Contact Page");
});

router.navigate("/about"); // Output: "About Page"

위의 예시 코드에서는 router 객체를 생성하여 addRoute 메소드를 통해 경로와 콜백 함수를 추가하고, navigate 메소드를 통해 해당 경로에 맞는 콜백 함수를 실행합니다. ‘this’ 키워드를 사용하여 현재 객체를 참조하며, router 객체 내의 routes 배열에 경로와 콜백 함수를 저장합니다.

2. 클래스를 사용한 라우팅 처리

class Router {
  constructor() {
    this.routes = [];
  }

  addRoute(path, callback) {
    this.routes.push({ path, callback });
  }

  navigate(path) {
    const matchedRoute = this.routes.find(route => route.path === path);
    if (matchedRoute) {
      matchedRoute.callback();
    } else {
      console.log("404 - Not Found");
    }
  }
}

const router = new Router();

router.addRoute("/", () => {
  console.log("Home Page");
});

router.addRoute("/about", () => {
  console.log("About Page");
});

router.addRoute("/contact", () => {
  console.log("Contact Page");
});

router.navigate("/contact"); // Output: "Contact Page"

위의 예시 코드에서는 Router 클래스를 정의하고 생성자에서 routes 배열을 초기화합니다. 클래스 내에 addRoutenavigate 메소드를 정의하여 라우팅 처리를 수행합니다. ‘this’ 키워드는 클래스의 인스턴스를 참조하며, 생성한 router 객체를 통해 라우팅 기능을 사용합니다.

이렇게 ‘this’ 키워드를 활용하여 자바스크립트에서 간편하게 라우팅 처리를 할 수 있습니다.

#javascript #라우팅