자바스크립트 들어가기 5

심민기·2022년 4월 9일
0

자바스크립트

목록 보기
6/11

객체지향 프로그래밍.

객체, 추상화. 부품화 재활용 가능 은닉화, 캡슐화 , 인터페이스

생성자와 new

{}만으로 비어있는 객체를 만드는 것이다.

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

이렇게 하면 분산되어 있어서 가시성이 안좋음.

var person = {
  'name' : 'egoing',
  'introduce' : function(){
      return 'My name is '+this.name;
  }
}
document.write(person.introduce());

{}안에서 프로퍼티와 메소드를 정의하여 중복을 없앤다.

생성자

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

함수 호출시 new를 붙이면 새로운 객체를 만드러서 리턴한다.

function A(){}로 빈 함수를 만들고 이를
var a = A(); 그냥 할당, 그리고 a를 부르면 undefined, 값이 없다 뜬다 이는 애초에 A함수가 값이 없으므로 그러나.

var a1 = new A();로 생성자를 쓰고 a1을 부르면 A {}라고 출력되어 a1이 A함수(객체)를 가지고 있다고 뜬다. 이는 var a1 = {}으로 객체를 만든 것과 비슷한 효과를 낸다.

자바스크립트에서는 클래스가 없다. 함수에 new를 붙이면 리턴값이 객체가 된다.

이런식으로 생성자에서 객체의 프로퍼티를 정의 하는 걸 초기화라고 한다.

전역객체

모든 객체는 전역객체의 프로퍼티다. 모든 전역변수, 함수는 사실 window객체의 프로퍼티다. 객체가 없는 것처럼 보이는 것도 사실 window의 프로퍼티인 것.

This

함수 내에서 함수 호출 맥락을 의미한다 . 맥락-- 상황에 따라 달라짐. 함수 어떻게 호출하냐에 따라 this가 가리키는 대상이 달라짐.

자바스크립트는 함수와 객체 관계가 느슨하므로 this가 이 둘을 연결시켜주는 역할을 한다.

this는 전역객체인 window와 같다.

function func(){
    if(window === this){
        document.write("window === this");
    }
}
func(); 

결과는 window === this

객체에 속한 메소드의 this는 객체를 가리킨다.

var o = {
    func : function(){
        if(o === this){
            document.write("o === this");
        }
    }
}
o.func();   

결과는 o ===this

생성자와 this

var funcThis = null; 
 
function Func(){
    funcThis = this;
}
var o1 = Func();
if(funcThis === window){
    document.write('window <br />');
}
 
var o2 = new Func();
if(funcThis === o2){
    document.write('o2 <br />');
}

결과는 window o2

생성자는 빈 객체를 만든다. 그리고 이 객체내에서 this는 만들어진 객체를 가르킨다.
생성자가 실행되기 전까지는 객체는 변수에도 할당될 수 없기 때문에 this가 아니면 객체에 대한 어떠한 작업을 할 수 없다.

함수의 메소드인 apply, call을 이용하면 this의 값을 제어할 수 있다.

var o = {}
var p = {}
function func(){
    switch(this){
        case o:
            document.write('o<br />');
            break;
        case p:
            document.write('p<br />');
            break;
        case window:
            document.write('window<br />');
            break;          
    }
}
func();
func.apply(o);
func.apply(p);

결과는 window o p다.
그냥 함수로 호출하면 this는 window가 된다.
apply를 사용하면 인자를 적용할 수 있다.

일반적으로 객체에서 객체와 메소드는 긴밀하게 엮인 관계(마스터 - 슬레이브)
그러나 apply등을 쓰면 이러한 관계를 더 자유롭게 할 수 있다.

상속

기존의 로직을 이어받는 것.
function Person(name){this.name = name;}
Person.prototype.name=null;
Person.prototype.introduce = function(){return 'My name is '+this.name;}
var p1 = new Person('egoing');
document.write(p1.introduce()+"<br />");

prototype이라는 프로퍼티(약속된 값), 상속을 위한 기본적인 준비.

function Person(name){
  this.name = name;
}
Person.prototype.name=null;
Person.prototype.introduce = function(){
  return 'My name is '+this.name; 
}
여기서 사람 함수에 대해 정리
function Programmer(name){
  this.name = name;
}
Programmer.prototype = new Person();
상속.
var p1 = new Programmer('egoing');
document.write(p1.introduce()+"<br />");

person을 new하게 만들어서 그 객체를 prototype에 넣고 p1은 그러한 programmer를 새로운 객체로 받은 것

이는 상속한 것이므로 기능을 추가하여 발전시킬수 있다 위의 코드에

Programmer.prototype.coding = function(){
return "hello world";
}를 넣으면 새로운 메소드 코딩이 추가된 것이다.

그래서 프로토 타입이 뭔데??

prototype은 그 용도가 약속되어 있는 특수한 프로퍼티.
function Ultra(){}
Ultra.prototype.ultraProp = true;
 
function Super(){}
Super.prototype = new Ultra();
 
function Sub(){}
Sub.prototype = new Super();
 
var o = new Sub();
console.log(o.ultraProp);

결과는 참이다.
상속받으려 할때 프로토 타입을 바로 쓰면 값이 나중에 문제가 생기니 생성자를 통해 만들어낸 복제본을 이용해야 한다.

    profile
    왕초보

    0개의 댓글

    관련 채용 정보