Computer >> 컴퓨터 >  >> 프로그램 작성 >> JavaScript

JavaScript에서 객체에 속성과 메서드를 추가하는 방법은 무엇입니까?


JavaScript에서 개체에 속성과 메서드를 추가하려면 프로토타입을 사용하세요. 재산.

예시

프로토타입으로 작업하는 방법을 배우기 위해 다음 코드를 실행할 수 있습니다 −

<html>
   <head>
      <title>JavaScript prototype property</title>
      <script>
         function book(title, author) {
            this.title = title;
            this.author = author;
         }
      </script>
   </head>
   <body>
      <script>
         var myBook = new book("Amit", "Java");
         book.prototype.price = null;
         myBook.price = 500;

         document.write("Book title is : " + myBook.title + "<br>");
         document.write("Book author is : " + myBook.author + "<br>");
         document.write("Book price is : " + myBook.price + "<br>");
      </script>
   </body>
</html>