남과 같이 해선 남 이상이 될 수 없다.

JavaScript

2021/05/30 자바스크립트

맨동 2021. 5. 30. 16:20
728x90

보간법

const age = 25
console.log("I'm" + age + "years")
console.log(`I'm ${age} years`)

//I'm25years
//I'm 25 years

백틱 기호를 사용하면 간단하게 변수 값을 문자열에 삽입 할 수 있다!

 

this

일반함수는 호출 위치에 따라 this 정의하고

화살표함수는 자신이 선언된 함수 범위에서 this 정의한다.

const user = {
  name: 'Kim',
  normal: function () {
    console.log(this.name)
  },
  arrow: () => {
    console.log(this.name);
  }
}
user.normal() //Kim
user.arrow()  //undefined
const user = {
  name: 'Kim',
  normal: function () {
    setTimeout(() => {
      console.log(this.name)
    }, 1000)
  }
}
user.normal() //Kim

화살표함수를 감싸고 있는 함수범위에서 this가 정의되고,

그 함수부분의 this 는 일반함수가 정의된 userthis가 된다.

 

Classes

ES6에서 등장!

// function User(first, last) {
//   this.firstName = first
//   this.lastName = last
// }
// User.prototype.getFullName = function () {
//   return `${this.firstName} ${this.lastName}`
// }

class User {
  constructor(first, last) {
    this.firstName = first
    this.lastName = last
  }
  getFullName() {
    return `${this.firstName} ${this.lastName}`
  }
}

const kim = new User('Dong', 'Kim')
console.log(kim.getFullName()) // Dong Kim

 

class 키워드를 사용하면 훨씬 깔끔하게 구현할 수 있다.

 

확장(상속)

class Vehicle {
  constructor(name, wheel) {
    this.name = name
    this.wheel = wheel
  }
}
const myVehicle = new Vehicle('운송수단', 2)
console.log(myVehicle) //Vehicle {name: "운송수단", wheel: 2}

class Bicycle extends Vehicle {
  constructor(name, wheel) {
    //super는 확장된 클래스 Vehicle을 의미
    super(name, wheel) 
  }
}
const myBicycle = new Bicycle('삼천리', 2)
console.log(myBicycle) //Bicycle {name: "삼천리", wheel: 2}


class Car extends Vehicle {
  constructor(name, wheel, license) {
    super(name, wheel)
    this.license = license
  }
}
const myCar = new Car('벤츠', 4, '운전면허증') //Car {name: "벤츠", wheel: 4, license: "운전면허증"}
console.log(myCar)

확장된 클래스는 super 라는 함수를 통해 내부에서 실행이 가능하다.

728x90

'JavaScript' 카테고리의 다른 글

2021/05/31 -2 자바스크립트  (0) 2021.05.31
2021/05/31 자바스크립트  (0) 2021.05.31
2021/05/28 자바스크립트  (0) 2021.05.28
21/05/27 자바스크립트  (0) 2021.05.27
자바스크립트: Math  (0) 2021.05.27