티스토리 뷰

 [javascript 11강] 객체 심화



저번글에서 객체에 대해서 알아보았습니다.

이번글에서는 저번글에서 접한 객체에 대해서 심화적으로 다루어 보겠습니다.

글에 들어가기전 부족한부분이 있다면 이전글을 참고해주세요!


 이전 글 링크 



 함수를 이용한 객체생성


자바스크립트 함수에서는 return 을 사용할수 있었습니다.

return 을 사용하여 객체를 반환해주어 객체를 생성할수있습니다.


 사용방법 및 문법 


function 함수명(){

var 객체명 = {

...

};

return 객체명;

}



 예제 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript">
    
            function createPerson(){
                
                var person = {
                    height:180,
                    weight:80,
                    fn: function (x,y){
                        console.log("난 덧샘을 잘하지! 두수의 합은 " + (x+y) +" 야!");
                    }
                }
                
                return person;
            }
        
            var person1 = createPerson();
            
            for(var key in person1){
                
                console.log("key:" + key);
                console.log("key값:" + person1[key]);
                
            }
            
        </script>
    </head>
    <body>
    </body>
</html>
cs


 실행결과 및 설명 

 


           function createPerson(){
                
                var person = {
                    height:180,
                    weight:80,
                    fn: function (x,y){
                        console.log("난 덧샘을 잘하지! 두수의 합은 " + (x+y) +" 야!");
                    }
                }
                
                return person;
            }

createPerson 이라는 함수를 만들고

함수안에는 person 이라는 객체를 만들어 주었습니다.

그다음 return 값으로 person 을 반환해 줍니다.


           var person1 = createPerson();

변수 person1 을 생성하면서 createPerson 함수를 실행하여 할당해 주었습니다.


           for(var key in person1){
                
                console.log("key:" + key);
                console.log("key값:" + person1[key]);
                
            }

person1 에 객체가 잘 생성되었나 확인을 하기위해 for in 을 이용하여 person1 의 속성을 출력해보았습니다.

그결과 잘 생성되어 위와같이 출력되는것을 확인할수 있습니다.




 생성자를 이용한 객체 생성


javascript 도 생성자를 지원합니다.

즉 new 키워드를 사용하여 객체를 만들수 있습니다.

이때 주의하실점은 객체를 함수로 만들어야 하고 속성또한 대입연산자를 사용합니다.


 사용방법 및 문법 


1. 생성자를 사용할 객체 만드는법


function 함수명(){

this.속성명1 또는 함수명1 = 속성값 또는 함수;

this.속성명2 또는 함수명2 = 속성값 또는 함수;

...

this.속성명10 또는 함수명10 : 속성값 또는 함수;

};


2. 생성자를 사용해 객체 생성


new 생성자 함수명();



 예제 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript">
    
            function createPerson(height,weight){
                
                this.height = height;
                this.weight = weight;
                this.fn = function (x,y){
                    console.log("난 덧샘을 잘하지! 두수의 합은 " + (x+y) +" 야!");
            
                };
                
            }
            
            var person1 = new createPerson(180,80);
            
            for(var key in person1){
                
                console.log("key:" + key);
                console.log("key값:" + person1[key]);
            }
            
        </script>
    </head>
    <body>
    </body>
</html>
cs


 실행결과 및 설명 

 


           function createPerson(height,weight){
                
                this.height = height;
                this.weight = weight;
                this.fn = function (x,y){
                    console.log("난 덧샘을 잘하지! 두수의 합은 " + (x+y) +" 야!");
            
                };
                
            }

createPerson 이라고 함수명을 적어주고 매개변수를 height, weight 의 값을 받기위해 적어주었습니다.

그다음 this.height 에 매개변수 height을 할당해주고..

그다음 this.weight 에 매개변수 weight 을 할당해주고

this.fn 에 함수를 할당해 주었습니다.


           var person1 = new createPerson(180,80);

person1 이라는 변수를 만들어주며 할당값으로 new 키워드를 사용하여 createPerson 을 생성과동시해 180,80 이라는 값을 넘겨주었습니다.


           for(var key in person1){
                
                console.log("key:" + key);
                console.log("key값:" + person1[key]);
            }

다음 for ~ in 을 활용하여 객체가 생성되었나 속성값들을 확인해보았습니다.

그결과 객체는 생성되었고 위의 이미지와 같은 결과를 확인할수 있습니다.




 prototype(프로토타입)


prototype 은 javascript 에서만 있는 기능으로 자원의 낭비를 줄이기 위해 있는 기능입니다.

javascript 에는 prototype 이라는 공유된 공간이 있습니다.

만약 객체에 같은 기능을 하는 함수가 있다면 객체를 생성할때마다 똑같은 함수가 계속해서 생성될것입니다.

어짜피 똑같은 기능인대 쓸모없이 계속 생성할 필요는 없겟죠..

그렇기 때문에 이러한 단점을 극복하고자 prototype 이 있는것입니다.


 사용방법 및 문법 


객체 생성후


객체명.prototype.함수명 = function () {};



 예제 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript">
    
            function createPerson(height,weight){
                
                this.height = height;
                this.weight = weight;
                
                
            }
            
            createPerson.prototype.fn = function (x,y){
                console.log("난 덧샘을 잘하지! 두수의 합은 " + (x+y) +" 야!");
        
            };
            
            var person1 = new createPerson(180,80);
            person1.fn(3,2);
            
            var person2 = new createPerson(180,80);
            person2.fn(1,2);
            
        </script>
    </head>
    <body>
    </body>
</html>
cs


 실행결과 및 설명 

 


           function createPerson(height,weight){
                
                this.height = height;
                this.weight = weight;
                
                
            }

createPerson 이라는 객체생성 함수를 만들었습니다.


           createPerson.prototype.fn = function (x,y){
                console.log("난 덧샘을 잘하지! 두수의 합은 " + (x+y) +" 야!");
        
            };

그다음 프로토타입 공간에 함수를 넣기위해  createPerson.prototype.fn 라고 적고 두수를 더하는 함수를 할당해주었습니다.


           var person1 = new createPerson(180,80);
            person1.fn(3,2);
            
            var person2 = new createPerson(180,80);
            person2.fn(1,2);

그다음 person1 과 pesrson2 라는 변수에 객체를 각각 생성하고..

객체마다 프로토타입으로 설정한 fn 의 함수가 실행되는지 person1.fn(3,2); , person2.fn(1,2); 각각 실행해 보았습니다.

그결과 각각실행되는것을 확인할수 있으며 위와같 이미지의 결과를 확인할수 있습니다.




 getter, setter 함수


getter 와 setter 함수는 외부에서 객체 내부의 변수에 접근하기 위한 함수입니다.

getter 을 사용하여 값을 갖어오고..

setter 을 사용하여 값을 넣어줍니다.

java 를 하셧다면 빈즈를 생각하시면 됩니다.


 사용방법 및 문법 


function 함수명(){


var 접근못하게할변수명1 = "값";

var 접근못하게할변수명2 = "값";

...


속성명1 또는 함수명1 = 속성값 또는 함수;

속성명2 또는 함수명2 = 속성값 또는 함수;

...

속성명10 또는 함수명10 : 속성값 또는 함수;


}



 예제 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript">
    
            function createPerson(){
                
                var height = 0;
                var weight = 0;
 
                this.setInformation = function (h,w){
                    this.height = h;
                    this.weight = w;
                }
                
                this.getHeight = function(){
                    return this.height;
                }
                
                this.getWeight = function(){
                    return this.weight;
                }
                
            }
            
            
            var person1 = new createPerson(180,80);
            person1.setInformation(180,80);
            console.log("키:" + person1.getHeight());
            console.log("몸무게:" + person1.getWeight());
            
            
        </script>
    </head>
    <body>
    </body>
</html>
cs


 실행결과 및 설명 



           function createPerson(){
                
                var height = 0;
                var weight = 0;
 
                this.setInformation = function (h,w){
                    this.height = h;
                    this.weight = w;
                }
                
                this.getHeight = function(){
                    return this.height;
                }
                
                this.getWeight = function(){
                    return this.weight;
                }
                
            }

createPerson 이라는 함수명의 함수가 있습니다.

안에는 변수 height, weight 가 있습니다.

(속성으로 만들시 속성값을 조절할수 있지만.. 변수로 생성하면 외부에서는 직접 접근하여 변경할수 없습니다.)

그다음 height, weight 값을 넣어주기위한 set 함수인 setInformation 함수를 만들어 주었습니다.

그리고 height, weight 값을 출력하기위한 get 함수인 getHeight 함수와 getWeight 함수를 만들어 주었습니다.

 

           var person1 = new createPerson(180,80);
            person1.setInformation(180,80);
            console.log("키:" + person1.getHeight());
            console.log("몸무게:" + person1.getWeight());

그다음 person1 이라는 변수에 new 키워드를 사용하여 createPerson 객체를 생성하였고..

set를 사용하여 값을 넣어주기 위해 person1.setInformation 을 실행하고 값을 180, 80 을 주었습니다.

그다음 get를 사용하기위해  person1.getHight, person1.getWeight 를 실행하여 콘솔로 출력해보았습니다.

그결과 set 와 get 가 작동한값을 위와같은 이미지로 확인할수 있습니다.




 글을 마치며..


이번글을 통해 객체를 생성하는 다양한 방법 및 심화적인 내용에 대해서 알아보았습니다.

객체를 생성하는 방법을 하나만 알고 있으면 나중에 공동작업간에 힘든점이 많이 있습니다.

그렇기때문에 모두 알아야하는 필수 내용입니다. 꼭! 이해하고 넘어가셔야합니다.

이상으로 글을 마치도록 하겠습니다. 수고하세요!


도움이 되셨다면 로그인 없이 가능한

아래 하트♥공감 버튼을 꾹 눌러주세요! 




'Programming > JavaScript, jQuery' 카테고리의 다른 글

[javascript 13강] BOM (브라우저 객체)  (0) 2019.02.18
[javascript 12강] 내장객체  (0) 2019.02.17
[javascript 10강] 객체  (0) 2019.02.13
[javascript 9강] 함수 심화  (0) 2019.02.12
[javascript 8강] 함수  (0) 2019.02.12
댓글