class (객체 데이터) = 속성(변수) + 메소드(함수)
ex) 스타벅스 슬라이드 (swiper) 예시
main.js
const test = { // 객체 데이터 firstName: 'Hi' // 속성 lastName: 'Kim' getFullName: function () { // 메소드 return `${this.firstName} ${this.lastName}` // 백깃으로 고간 == this 대신 test 넣어도 되지만 객체 이름 명시 권장 X (변경가능) } }
console.log(test.getFullName)
function User(first,last) { this.firstName = first this.lastName = last }
생성자함수 (객체데이터 생성)
const hello = new User('hello', 'Kim') // 생성자 const amy = new User('hello', 'Kim') //여기서 hello와 amy = instance console.log(hello) console.log(amy)
prototype
User.prototype.getFullName = function () { return `${this.firstName} ${this.lastName} }
prototye 숨겨진 속성
getFullName할당해주면 몇개의 객체 만들던 해당 함수는 메모리에 한 번만 만들어지기 때문에 console.에서 호출한 함수는 해당 프로토타입을 참조하는 식으로 메모리 사용
배열 내부 프로토 함수
const a = [1,2,3] a.includes(4) // 배열 데이터 안에 4가 있는지 확인 false 출력
스타벅스 swiper
new Swiper ('.notice-line .swiper-container', { //생성자 함수 // 반환된 내용을 인스턴스로 받지 않아도 설정된 로직으로 슬라이드 요소 동작가능 // 인수로 문자데이터 넣고 두번째 인수로 객체데이터 넣음 // 두 개 인수를 Swiper 내부 선언된 함수에서 특정 매개변수로 받아서 슬라이드 만드는 로직으로 사용 direction: autoplay: true loop: true
this
const hello = { name: 'hell', normal: function () { console.log(this.name) }, arrow: () => { console.log(this.name) } }
hello.normal() O // normal에서 호출되고 그 앞 객체데이터 (this)에서 name 꺼냄 hello.arrow() undefined // 선언된 범위가 정의되어있지 않음 (선언될때 this 알 수 있음, 함수 범위에서 정의되기 때문)
const amy = { name: 'Amy', normal: hello.normal, arrow: hello.arrow } amy.normal() O 호출될때 연결된 객체는 amy이기 때문에 Amy return amy.arrow() X 선언된 위치에서 this가 정의되기 때문에 undefined
프로토타입 형태로 만들어줘도 결과 똑같음!
const time = { name: 'hello', timeout: function () { // setTimeout(함수, 시간) setTimeout(function () { console.log(this.name) // undefined }, 2000) } } timer.timeout()
const time = { name: 'hello', timeout: function () { // setTimeout(함수, 시간) setTimeout(function () => { console.log(this.name) // O }, 2000) } } timer.timeout()
setTimeout / setInterval 의 경우 call back으로 화살표 함수를 사용하는 것이 활용도가 높음.
객체 데이터 내부에서 콜론 + function키워드 생략가능
const hello = { name: 'hello' normal () [ console.log(this.name) } } heropy.normal()
ES6 Classes
function User(first,last) { this.firstName = first this.lastName = last } User.prototype.getFullName = function () { return `${this.firstName} ${this.lastName} } const hello = new User('hello', 'Kim') const amy = new User('hello', 'Kim') console.log(hello) console.log(amy)
다른 언어의 Class와 비슷하게 사용하기 시작
class User { constructor(first, last) { this.firstName = first this.lastName = last } getFullName() { return `${this.firstName} ${this.lastName}` } }
Class
class Vehicle { constructor(name,wheel) { this.name = name this.wheel = wheel } } const myVehicel = new Vehicle('운송수단', 2)
확장 (상속)
class Bicycle extends Vehicle { constructor(name,wheel) { super(name, wheel) // super자리에서 확장된 클래스 실행됨 } } const myBi = new Bicycle('삼천리', 2) const herBi = new Bicycle('세발', 3)
확장 (상속) + this
class Car extends Vehicle { constructor(name,wheel, license) { super(name, wheel) this.license = license } } const myCar = new Car('벤츠', 4, true)