Skip to content

Commit 0f6ced5

Browse files
committed
Create 임성은_생성자와 new.md
1 parent 52c6d85 commit 0f6ced5

File tree

1 file changed

+94
-0
lines changed

1 file changed

+94
-0
lines changed
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#함수지향
2+
3+
작성자 : 임성은
4+
5+
작성일 : 2016-01-29 20:50
6+
7+
* **객체지향**
8+
- 객체지향 프로그래밍
9+
- 생성자와 new
10+
- 전역객체
11+
- this
12+
- 상속
13+
- prototype
14+
- 표준 내장 객체의 확장
15+
- Object
16+
- 데이터 타입
17+
- 참조
18+
19+
###생성자와 new
20+
**생성자(constructor)**는 객체를 만드는 역할을 하는 함수다.<br />
21+
자바스크립트에서 함수는 재사용 가능한 로직의 묶음이 아니라 **객체를 만드는 창조자**라고 할 수 있다.<br />
22+
객체의 구조를 재활용할 수 있는 방법이 필요할 때 사용하는 것이 생성자다. <br />
23+
일반적인 객체지향 언어에서 생성자는 클래스의 소속이다. 하지만 자바스크립트에서 **객체를 만드는 주체**는 함수다.<br />
24+
함수에 new를 붙이는 것을 통해서 객체를 만들 수 있다는 점은 자바스크립트에서 함수의 위상을 암시하는 단서이면서 또 자바스크립트가 추구하는 자유로움을 보여주는 사례라고 할 수 있다.<br />
25+
함수를 호출할 때 **new**을 붙이면 새로운 객체를 만든 후에 이를 리턴한다. <br />
26+
생성자 내에서 객체의 프로퍼티를 정의하는 작업을 **초기화**라고 한다. 이를 통해서 코드의 재사용성이 대폭 높아진다.<br />
27+
또한 생성자 함수는 일반함수와 구분하기 위해서 **첫글자를 대문자**로 표시한다. <br />
28+
29+
###예시
30+
31+
####예시 01
32+
33+
```javascript
34+
<script>
35+
function Person(){}
36+
var p = new Person();
37+
p.name = 'egoing';
38+
p.introduce = function(){
39+
return 'My name is '+this.name;
40+
}
41+
document.write(p.introduce());
42+
</script>
43+
```
44+
위의 코드는 새로운 객체를 변수 p에 담았다. 여러사람을 위한 객체를 만든다면 아래와 같이 코드를 작성해야 할 것이다.<br />
45+
===> 실행결과 : My name is egoing
46+
47+
[==> CondePen 확인](http://codepen.io/lseeee/pen/GoGROd)
48+
49+
####예시 02
50+
51+
```javascript
52+
<script>
53+
function Person(){}
54+
var p1 = new Person();
55+
p1.name = 'egoing';
56+
p1.introduce = function(){
57+
return 'My name is '+this.name;
58+
}
59+
document.write(p1.introduce()+"<br />");
60+
61+
var p2 = new Person();
62+
p2.name = 'leezche';
63+
p2.introduce = function(){
64+
return 'My name is '+this.name;
65+
}
66+
document.write(p2.introduce());
67+
68+
//코드 개선
69+
70+
function Person(name){
71+
this.name = name;
72+
this.introduce = function(){
73+
return 'My name is '+this.name;
74+
}
75+
}
76+
var p1 = new Person('egoing');
77+
document.write(p1.introduce()+"<br />");
78+
79+
var p2 = new Person('leezche');
80+
document.write(p2.introduce());
81+
</script>
82+
```
83+
메소드는 객체가 수행해야 할 행동이다. 아래의 코드는 String 객체의 toUpperCase() 메소드를 사용하여 텍스트를 대문자로 출력하는 코드이다.<br />
84+
===> 실행결과 :
85+
My name is egoing<br />
86+
My name is leezche<br />
87+
My name is egoing<br />
88+
My name is leezche
89+
90+
[==> CondePen 확인](http://codepen.io/lseeee/pen/PZaoEB)
91+
92+
##참고
93+
[생성자와 new] https://opentutorials.org/module/532/6570][생성자와 new]
94+
[생성자와 new]:https://opentutorials.org/module/532/6570

0 commit comments

Comments
 (0)