class
프로토타입기반언어
- 참고사이트
- 객체는 함수를 통해서 만들어진다.
- String, Array 등 모두 함수로 정의되어 있다. “typeof String” 의 결과는 “f”
- 함수를 정의하면 함수만 생성되는 것이 아니라 Prototype Object도 같이 생성 함수정의
- Prototype Object는 일반적인 객체이므로 속성을 마음대로 추가/삭제 할 수 있습니다.
- 함수정의실습
- 프로토타입 = prototype Link + prototype Object
프로토타입 링크
: 인스턴스를 생성할 때 프로토타입에 대한 연결을 생성
객체생성
-
객체리터럴(Object 생성자의 축약형)
var emp = {} -
Object 생성자함수
var emp = new Object() -
사용자 정의 생성자 함수
function Emp(){}
var emp = new Emp();
클래스
- 객체 리터럴보다는 우수
- ES6에서 클래스 문법이 추가됨. 클래스 기반으로 바뀐 것은 아님.
- 상속이 가능
- class 키워드 사용
class Estimate {
constructor(param){
this.unit = param;
}
getEstimate(unittype, width, height){
let priceinfo = this.unit.find(item=>item.type == unittype);
return priceinfo.price*width*height;
}
addUnit(unit){
unit.push(unit);
}
}
let unitinfo = [
{ type: 'wood', price:100 },
{ type: 'iron', price:300 },
{ type: 'plastic', price:200 }
];
const estimator = new Estimate(unitinfo);
let result = estimator.getEstimate('wood',20,20);
console.log(result);
클래스 상속
실행컨텍스트
- 실행컨텍스트를 이해하면 스코프를 기반으로 식별자와 식별자에 바인된 값을 관리하는 방법, 호이스팅이 발생하는 이유, 클로저의 동작 방식, 태스크 뷰와 함께 동작하는 이벤트 핸들러와 비동기 처리의 동작방식을 이해할 수 있다.
- 소스코드 : 전역코드, 함수코드, 모듈코드, eval코드
- 소스코드 평가와 실행
- 실행컨텍스트를 생성, this 바인딩
- 변수, 함수 등의 선언문만 먼저 실행하여 컨텍스트가 관리하는 스코프에 등록
- 선언문을 제외한 소스코드가 순차적으로 실행(런타임)
- 소스코드에 실행에 필요한 정보(변수,함수)는 실행 컨테스트가 관리하는 스코프에서 검색해서 취득한다.
this 컨텍스트 범위와 바인딩
- this는 객체 자신을 가리키는 지시자
- this 지시자는 객체 메서드를 호출할 때 메서드를 호출한 객체에 대한 정보를 암시적으로 this 파라미터로 함께 전달. 파라미터와 같은 특징을 가짐
- 함수 안에서만 유효하며 메서드 안에서 별도의 내부 함수를 추가선언해서 사용하거나 객체 외부 함수를 호출하는 경우 다시 호출된 함수 안에서는 this 지시자로 객체에 접근할 수 없다. 접근하려면 this를 명시적으로 파라미터로 넘겨야 한다.(bind() 사용)
- 실습파일 : this(장바구니)
- 실습파일 : this(장바구니)
Button2 = function(elementid) {
var btn = this;
this.element = document.getElementById(elementid);
this.element.addEventListener("mouseover", this.doMouseOver);
this.element.addEventListener("mouseout", this.doMouseOut);
//this.doMouseOut.bind(btn)
}
Button2.prototype = {
doMouseOver : function(e) {
console.log('over');
this.element.style.backgroundColor = '#999';
}
,
doMouseOut : function(e) {
console.log('out');
this.element.style.backgroundColor = '#fff';
}
}
객체의 단축 속성명
let name = '라이언'
let age = 5;
let getName = function(){ return this.name}
let friends = {name, age, getName} //{name:name, age:age, getName:getName}
console.log(friends.getName())
단축 메서드명
let calc = { add(a,b){return a+b},
multiply(a,b){return a*b},
subtract(a,b){return a-b},
}
console.log(calc.add(1,2))
계산된 속성명
- []로 감싸면 속성명을 동적으로 지정
let idx = 0;
let obj = { ["name"+ ++idx]:idx , ["name"+ ++idx]:idx , ["name"+ ++idx]:idx }
console.log(obj)