자바스크립트 - ES6

이용일·2022년 7월 17일
0

javascript

목록 보기
1/1

1. 객체 초기화

let name="noona"
let age =17
let cute = true
let person = {name, age, cute} 
// let person = {name:name, age:age, cute:cute}와 같다

2. Destructuring

let person = {    name:"noona",   age:17,    cute:true}
let {name, age, cute} =  person
/* let name = person.name   let age = person.age   let cute = person.cute   와 같다 */

let array = [1,2,3]
let [a,b,c] = array
/* let a = array[0]   let b = array[1]   let c = array[2]   와 같다 */

3. Rest destructuring

let person = {    name:"noona",    age:17,    cute:true}
let {name, ...rest} = person
console.log(rest) // {age:17, cute:true}
let array = [1,2,3]
let [a,...rest] = array console.log(rest)//[2,3]

4. Spread

let a = [1,2]
let b = [3,4]
let c = [5,6]
let result = [...a,...b,...c] // [1,2,3,4,5,6]

5. Template Literal

let name ="noona"
console.log(`제 이름은 ${name}입니다`)

6. 화살표 함수

화살표 함수 표현식은 기존의 function 표현방식보다 간결하게 함수를 표현할 수 있다.
화살표 함수는 항상 익명이며, 자신의 this, arguments, super을 바인딩하지 않는다.자신만의 this를 생성하지 않고 자신을 포함하고 있는 context의 this를 이어 받는다.

let foo =()=>{
		console.log("hello")
 }
let zoo =()=>Date.now()
/* function zoo(){
	 return Date.now() 
 } 와 같음  */
let koo = (a,b) =>{ 
		let result = a*b    
		return result
 }
//또는let koo = (a,b) =>a*b
//로도 표현 가능

화살표 함수를 쓰면 안되는 경우

  • object{객체}안에 함수 정의 시
const person = {    
points: 23,    
score: function(){
      this.points++; 
// 여기에선 화살표함수 쓰면 point가 증가 안함
//   화살표함수는 this가 없음
//  화살표함수에서의 this는 window임    }}
  • 프로토타입 함수
class Car {    
constructor(make, color) {       
this.make = make;       
this.color = color;    
}
}
let hyundai = new Car("noona","white")
Car.prototype.summary = function () {
    console.log( `This car is a ${this.make} in the colour ${this.colour}`)
} // 여기서 화살표함수를 쓰면 안됀다  hyundai.summary()

번외편 : this

자바스크립트에서 모든 일반함수는 실행될 때마다 함수 내부에 this라는 객체가 추가된다. 이때 this는 이 함수를 부른 객체이다.

let age = 20
var obj = { 
age:12, 
foo: function () {
   console.log(this.age)  
},
};
obj.foo()

참고

function으로 선언된 일반 함수들은 자바스크립트가 시작됨과 동시에 미리 메모리에 선언되어 기억되어진다(호이스팅개념) 따라서 함수를 선언전에 불러도 무관하다.
즉,

return addNumber(1)(2)(3); // 순서상관없음
  function addNumber(a) {
    return function (b) {
      return function (c) {
        return a + b + c;
      };
    };
  }

이거나

function addNumber(a) {
   return function (b) {
     return function (c) {
       return a + b + c;
     };
   };
 }
 return addNumber(1)(2)(3);
// 순서상관없음

이거나 결과는 같고 에러도 나오지 않는다.

하지만 화살표 함수는 function으로 선언된것이 아니기 때문에 그렇지 않다.
반드시 선언과 정의 후에 불러줘야한다.

따라서

return addNumber(1)(2)(3);
let addNumber=(a)=>(b)=> (c)=> a + b + c;

이렇게 작성을 할 경우 에러가 난다.

profile
프론트엔드 개발자가 되고싶어 공부하는 중

0개의 댓글