TIL no.19

손병진·2020년 8월 17일
0

TIL

목록 보기
19/22

객체지향이란?

  • 특정 기능과 연관된 변수와 메소드의 '객체'라는 집합으로 묶어놓는 방식(재활용성)
  • 추상화: 복잡함 속에서 필요한 관점만을 추출하는 행위
  • 부품화: 연관된 메소드와 그 메소드가 사용하는 변수들을 분류하고 그룹핑하는 것이다

생성자와 new

  • 효과적인 부품(객체)을 만드는 것이 목표

객체 생성(복습)

  • 객체 내의 변수를 property 라고 칭한다
  • 해당 값은 문자, 숫자, 함수(method) 등이 입력될 수 있다
var person = {}
person.name = 'egoing';// name : egoing
person.introduce = function(){// introduce : function(){}
    return 'My name is '+this.name;// this 해당 메소드가 속해있는 객체를 지칭
}
document.write(person.introduce());// My name is egoing

// 동일 의미 다른 표현
var person = {
    'name' : 'egoing',
    'introduce' : function(){
        return 'My name is '+this.name;
    }
}
document.write(person.introduce());

생성자와 new

  • 생성자(constructor): 객체를 만드는 역할의 함수
  • new + 함수p = (객체의)생성자p
function Person(){}
var p = Person();// undefined
// 함수 Person의 return 값이 없기 때문에 undefined

//하지만 new를 붙인다면?
var p = new Person();// Person {}
/* 비어있는 객체를 생성한다
var p = {} 해당 식과 같다고 할 수 있다*/

p.name = 'egoing';
p.introduce = function(){
    return 'My name is '+this.name; 
}
document.write(p.introduce());// My name is egoing

// 중복 문제 해결
function Person(name){
    this.name = name;
    this.introduce = function(){
        return 'My name is '+this.name; 
    }   
}// 변수 내의 메소드를 사전에 설정하여 여러번 작성하지 않아도 된다(초기화)

var p1 = new Person('egoing');
document.write(p1.introduce()+"<br />");
 
var p2 = new Person('leezche');
document.write(p2.introduce());
profile
https://castie.tistory.com

0개의 댓글