자바스크립트객체 (1)

이번 포스트에서는 자바스크립트의 객체에 대해서 알아볼텐데요 객체가 무엇인지는 알고계신다는 전제하에 실무 위주의 내용을 얘기해보도록 할거에요. 자바의 객체와 동일한 것이라고 생각하시면 되고 단지 사용법이 어떤지에 대해서 알고 넘어가는 정도로 습득하시면 될것 같습니다. 

객체의 속성

자바를 공부해 보신분들이라면 아시겠지만 객체 안에는 프리미티브 멤버변수나 다른 객체를 하나의 변수처럼 가지고 있습니다. 이런 멤버변수들을 자바스크립트에서는 속성이라고 얘기를 합니다. 그리고 그 속성들에 값을 넣는 방법은 다음과 같습니다.:
객체명.속성명 = 속성값;

예제:

아래 예제는 document객체의 title이라는 속성을 str변수에 할당하는 예제입니다. 

var str = document.title;

객체의 메소드

이번에는 메소드에 대해서 알아보죠.

예제:

아래 예제는 document객체 내부에 선언되어있는 write()메소드를 호출하는 예제입니다. 이미 여러번 보셨을 겁니다. hello world 뭐 이런 예제에서 말이죠.

document.write("This is test");


사용자 정의 객체

다 아시겠지만 모든 사용자정의 객체와 이미 정의되어있는 built-in 객체들은 Object라는 객체의 하위 클래스들입니다.

The new Operator:

아래 예제는 new 오퍼레이터를 이용해서 built-in JavaScript 객체들을 생성하는 것을 보여주고있습니다.

var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");


Object() 생성자:

생성자라는 것은 객체를 생성하고 초기화하는 메소드입니다. 위 예제에서 new Object(); 의 Object()는  Object객체의 생성자입니다. 이렇게 생성된 객체에 대한 레퍼런스를 var로 선언한 employee에 할당해주면 나중에 이 객체에 접근할 때 employee라는 이름으로 접근할 수 있습니다. 만약 employee가 이름과 나이를 속성으로 가지고 있다고 한다면 이런 것은 어떻게 값을 넣을 수 있을 까요? 속성은 변수가 아닙니다. 따라서 var키워드로 선언을 하지 않습니다. 아래 예제를 한번 보도록 하죠. 

예제 1:

아래 예제는 객체를 생성하고 그 객체의 속성을 정의해줍니다.

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object();   // Create the object
    book.subject = "Perl"; // Assign properties to the object
    book.author  = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
   document.write("Book name is : " + book.subject + "<br>");
   document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>

 

 

예제 2:

이번 예제는 사용자 정의 객체를 만드는 예제입니다. 여기서 this 키워드는 함수로 전달된 객체를 참조하는 역할을 합니다.

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
    this.title = title; 
    this.author  = author;
}
</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Perl", "Mohtashim");
   document.write("Book title is : " + myBook.title + "<br>");
   document.write("Book author is : " + myBook.author + "<br>");
</script>
</body>
</html>

 

 

객체의 메소드 정의하기

이번에는 객체의 메소드를 정의하는 방법을 알아보도록 하겠습니다.

예제:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// 객체의 메소드가 될 함수를 정의합니다.
function addPrice(amount){
    this.price = amount; 
}

function book(title, author){
    this.title = title; 
    this.author  = author;
    this.addPrice = addPrice; // 메소드를 속성으로 할당(선언)합니다.
}

</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Perl", "Mohtashim");
   myBook.addPrice(100);
   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>

 

 

with 키워드

with 키워드는 객체의 속성이나 메소드를 참조하기위한 단축키워드 같은 것입니다.

with에 파라미터로 전달된 객체는 해당 블락내에서 기본적인 참조변수처럼 동작합니다.따라서 해당 객체의 속성이나 메소드에 접근할 때 궂이 해당 객체이름과 점을 안찍어도 됩니다.

문법:

with (object){
    properties used without the object name and dot
}

예제:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">

// Define a function which will work as a method
function addPrice(amount){
    with(this){
       price = amount; 
    }
}
function book(title, author){
    this.title = title; 
    this.author  = author;
    this.price = 0;
    this.addPrice = addPrice; // Assign that method as property.
}
</script>
</head>
<body>
<script type="text/javascript">
   var myBook = new book("Perl", "Mohtashim");
   myBook.addPrice(100);
   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>

 

 

 

 

 

 Reference : http://www.tutorialspoint.com/javascript/javascript_objects.htm