Practice makes perfect

[JavaScript] JavaScript - 객체 본문

web/JavaScript

[JavaScript] JavaScript - 객체

kerpect 2020. 7. 9. 11:22

 객체 

: 객체는 관련된 데이터와 함수(일반적으로 여러 데이터와 함수로 이루어지는데, 객체 안에 있을 때는 보통 프로퍼티와 메소드라고 부릅니다)의 집합입니다. 

 

1. 객체의 생성 - 키:요소 

{ } (소괄호) 사이에 데이터를 key - value 로 넣음. 

 

 

 

2. 객체의 속성과 메서드 


속성 : 객체 내부에 있는 하나하나의 값.


- 객체의 속성이 가질 수 있는 자료형 - 

 

 

- 속성과 메서드의 구분 ( 변수 선언)

 

key ; value 로 저장하여 접근할 수 있도록 합니다. 

 

 

 

- this 키워드:자바스크립트는 this 키워드를 생략할 수 없다. 

  (this - 자신의 영역 안에 있는 메모리에 접근)  

 

 

3. 객체 한번에 모두 불러오기 

 

 

4. 객체와 관련된 키워드

 

in 키워드:해당 키가 객체 안에 있는지 확인(존재 유무) 

있으면 true , 없으면 false 출력.

 

with 키워드:복잡하게 사용해야 하는 코드를 짧게 줄여주는 키워드

 

- with 키워드를 사용하지 않은 경우

 

-  with 키워드를 사용한 경우

 

with로 객체를 불러와서 . student를 붙이지 않아도 같은 값을 출력 

 

 

5. 객체의 속성 추가와 제거 

동적 속성 추가/제거 : 처음 객체 생성하는 시점 이후에 객체의 속성을 추가하거나 제거 

 

- this 를 이용해서 key - value값을 가지고 와서 결과를 반환. 

- key != 'toString' :  toString은 출력되지 않도록 합니다. 

 

 

 

- 객체의 속성 제거

 

alert(student); 메서드 호출을 한것이 아닌데 결과 값을 잘 출력합니다. 그 이유는 주소값을 가지고 있는 참조변수를 넣으면 출력하도록 기능이 들어가있습니다. 

 

 

6. 생성자 함수 

- new 키워드를 사용해 객체를 생성할 수 있는 함수

- 생성자 함수를 사용한 객체의 생성과 출력

- 그냥 함수를 사용해 객체를 리턴하는 방법과 차이가 없어 보임

- 함수와 비교를 위해 첫글자를 대문자로 저장(약속)

- java의 참조자료형의 형태 이지만 javascript는 함수로 사용

- 반드시 this. 키워드를 붙여서 넣어줘야 함.

 

  function Student(name, korean, math, english, science){
	    // 속성
	    this.이름 = name;
	    this.국어 = korean;
	    this.수학 = math;
	    this.영어 = english;
	    this.과학 = science;
	    
	    // 메서드
	    this.getSum = function (){ // 정수의 총합
	    	return this.국어+this.수학+this.영어+this.과학;
	    };
	    
	    this.getAverage = function() { // 정수의 총합
	    	return this.getSum()/4; // 같은 영역 안에서 함수의 이름으로 출력 가능 
	    }
	    this.toString = function() { 
	    	return this.이름+':   '+this.getSum()+',   '+this.getAverage();
	    } // 데이터 출력(alert을 호출할 때, 함수가 들어가 있는 변수는 함수 없이 출력된다.)
    };

 	var students = []; //  [ ] : 배열 
    students.push(new Student('홍길동', 87, 98, 88, 95));
    students.push(new Student('홍길서', 92, 98, 96, 90));
    students.push(new Student('홍길남', 76, 78, 94, 90));
    students.push(new Student('홍길북', 68, 78, 84, 92));
    students.push(new Student('김길동', 84, 98, 88, 95));
    students.push(new Student('이길동', 87, 98, 88, 95));
    students.push(new Student('박길동', 87, 98, 88, 95));
    students.push(new Student('오길동', 87, 98, 88, 95));

    var output = '이름    총점    평균\n';
    for(var i in students){
    	output += students[i].toString()+'\n';
    }
    
    alert(output); 

- 생성자 안에 메서드도 함께 선언. 

 

- ouput 에 누적되어 저장하되, alert를 통해서 출력. 

 

 

 

 

 

7. 프로토타입 

- 생성자 함수를 사용해 생성된 객체가 공통으로 가지는 공간.
- 자바스크립트의 모든 함수는 변수 prototype을 갖고 prototype은 객체다.

- java의 static과 같은 기능 

 

  function Student(name, korean, math, english, science){
	    // 속성
	    this.이름 = name;
	    this.국어 = korean;
	    this.수학 = math;
	    this.영어 = english;
	    this.과학 = science;
    }
    
    Student.prototype.getSum = function(){ // 총합
    	return this.국어+this.수학+this.영어+this.과학;
    };
    
    Student.prototype.getAverage = function(){ // 평균
    	return this.getSum()/4;
    };
    
    Student.prototype.toString = function(){ // 출력 
    	return this.이름+':   '+this.getSum()+',   '+this.getAverage();
    };
    
    var students = []; // 배열 
    students.push(new Student('홍길동', 87, 98, 88, 95));
    students.push(new Student('홍길서', 92, 98, 96, 90));
    students.push(new Student('홍길남', 76, 78, 94, 90));
    students.push(new Student('홍길북', 68, 78, 84, 92));
    students.push(new Student('김길동', 84, 98, 88, 95));
    students.push(new Student('이길동', 87, 98, 88, 95));
    students.push(new Student('박길동', 87, 98, 88, 95));
    students.push(new Student('오길동', 87, 98, 88, 95));
    
    var output = '이름    총점    평균\n';
    for(var i in students){
    	output += students[i].toString()+'\n';
    }
    alert(output);

 

- 생성자에 필드만 선언하고 메서드는 프로토 타입으로 공통적으로 사용되므로 언제든지 필요한 곳에서 사용

- 코드상에서는 큰 변화는 없지만 구동상에 메모리를 효육적으로 사용 

 

 

 

 

8. instanceof 키워드  

- 인스턴스:생성자 함수를 통해 만들어진 객체.
- 해당 객체가 어떠한 생성자 함수를 통해 생성됐는지를 확인할 때 사용하는 키워드.

- 피연산자 2개 필요 = (참조변수  instanceof  자료형)

- 상속의 다형성에 의해서 지원

alert(student instanceof Student); 

alert(student instanceof Student); 

 

 

 

9. 상속

- 문법적으로 약속된 규칙은 없음. 

- 생성자 함수를 정의 하면서 필드에 담아주는 것이 가능한 것이 상속을 통해서 가능

  function Rectangle(w,h){ // 생성자 함수 (반드시 this.붙어야한다)
	    var width = w; // 함수안에서 사용하기 위한 지역 변수 선언(this(x), - field(x))
	    var height = h;  // 함수안에서 사용하기 위한 지역 변수 선언(this(x), - field(x))
	    
	    this.getWidth = function() {return width;} // 메서드 사용(this(0))
	    this.getHeight = function () {return height;} // 메서드 사용(this(0))
	    
	    this.setWidth = function(value){
	    	if(value < 0){
	    		throw '길이는 음수일 수 없습니다.';
	    	} else {
	    		width = value;
	    	}
	    }
	    
	    this.setHeight = function(value){
	    	if(value < 0){
	    		throw '길이는 음수일 수 없습니다.';
	    	} else {
	    		height = value;
	    	}
	    }
    }
	
    Rectangle.prototype.getArea = function () {
    	return this.getWidth() * this.getHeight();
    }
 
    
    function Square(length){
    	this.base = Rectangle;
    	this.base(length, length)
    }
    Square.prototype = Rectangle.prototype;
    
    var rectangle = new Rectangle(5, 7);
    var square = new Square(5);
    
    alert(rectangle.getArea());
    alert(square.getArea()); 

alert(rectangle.getArea());

 

  alert(square.getArea());