https://opentutorials.org/module/4047 를 참고하여 작성하였습니다.
JavaScript에 내장된 객체들-
예를들어 JSON객체, Date객체가 있다.
JSON.stringify()처럼 JSON객체안에 메서드를 사용 할 수 있다-(new를 하지않는건.. 아마 static이라 그런거 아닐까.)
1.사용자 선언 객체
constructor 함수를 만들어서 객체를 찍어낼수 있다.
//자바스크립트 내장객체인 Date
var startDate = new Date('2019-4-10') //'new'를 통해 새로운 객체를 만들 수 있다.
//사용자선언 객체
function Person(name, age) {
this.name = name;
this.age = age;
this.hello = function() {
return this.name + this.age + ‘안녕~’;
}
}
var sohee = new Person('sohee', 29)
sohee.hello()//소희 안녕~
2.객체 생성 이후, 특정 객체의 메서드를 수정하고 싶을때
function Person(name, age) {
this.name = name;
this.age = age;
this.hello = function() {
return this.name + this.age + ‘안녕’;
}
}
var sohee = new Person(‘sohee’, 29)
sohee.hello = function() {
return this.name + this.age + ‘안녕안녕안녕!!’;
}
sohee.hello()//소희29안녕안녕안녕!!
3.ProtoType으로 코드 재사용성 높이기.
모든 Person객체들이 ProtoType영역의 hello라는 메서드를 공유하기 때문에 메모리를 아낄 수 있다.
또한, hello라는 메서드를 다른 객체에서도 재사용 할 수 있다.
3-1. ProtyTYpe에 선언된 메서드를 재정의하기.
자바스크립트는 메서드가 호출되면 먼저 객체에서 찾고, 없으면 프로토타입 영역에서 찾는듯하다.
//3
function Person(name, age) {
this.name = name;
this.age = age;
// 위의 예제에서 hello메서드만 제외.
}
function hello(){
return this.name + '는 바보야~!';
}//다른 코드에서 재사용 가능
//ProtoType이라는 Person객체들의 공통된 공간에 메서드를 선언한다.
Person.prototype.hello = hello
var sohee = Person('sohee', 29)
sohee.hello()//sohee는 바보야~!
//3-1
//ProtoType에 선언된 메서드를 재정의하기.
sohee.hello = function(){
return this.name + ‘는 바보 아니야~’
}
sohee.hello()//소희는 바보 아니야~!
'Today I learned' 카테고리의 다른 글
MyBuilder 1일차 교육 정리 (0) | 2019.04.25 |
---|---|
HTTP request Parser 코드 분석(JAVA) (0) | 2019.04.22 |
sql 회귀학습 (0) | 2019.04.10 |
컬렉션 프레임워크 그리고 Iterator, Enumeration (0) | 2019.04.05 |
Mybatis 동적쿼리작성 (0) | 2019.03.22 |
댓글