[es6] javascript 문법 (2) 화살표함수

munju·2023년 4월 6일
1
post-thumbnail

ES6는 템플릿 리터럴 이라고 불리는 새로운 문자열 표기법을 도입하였는데,
템플릿 리터럴은 일반 문자열과 비슷해 보이지만 '또는 "같은 통상적인 따옴표 문자 대신 백틱 문자 '를 사용한다.

const template = 템플릿 리터럴은 '작은따옴표(single quotes)'와 "큰따옴표(double quotes)"를 혼용할 수 있다.;

<script>
	   const template = 
       `<ul class="nav-items">
            <li><a href="#home">Home</a></li>
            <li><a href="#home">News</a></li>
            <li><a href="#home">Contact</a></li>
            <li><a href="#home">About</a></li>
        </ul>`;
        console.log(template);
</script>
  1. 일반적인 문자열에서 줄바꿈은 허용되지 않으며 공백을 표현하기 위해서는 백슬래시로 시작하는 이스케이프 시퀀스를 사용해야한다. ES6템플릿 리터럴은 일반적인 문자열과 달리 여러줄에 걸쳐 문자열을 작성할 수 있으며, 템플릿 리터럴 내의 모든 공백은 있는 그대로 적용한다.
<script>
	const first = "Lee";
    const last = "Jo";
    //ES5: 문자열연결
    console.log('My name is ' + first + ' ' + last + '.');
</script>
  1. ES6 : String Interpolaton
    템플릿 리터럴은 +연산자를 사용하지 않아도 간단한 방법으로 새로운 문자열을
    삽입할 수 있는 기능을 제공한다.
<script>
    console.log(`1+1 = ${1+1}`);  // 1+1 = 2
    const name = 'Leee';
    console.log(`Hello ${name.toUpperCase()}`); //Hello Leee;
</script>
  1. ${expression}을 템플릿 대입문이라고 하는데,
    템플릿 대입문에서는 문자열 뿐만아니라 표현식도 할 수 있다.

Arrow Function(화살표함수)

키워드 대신 화살표 => 를 사용하여
간략한 방법으로 함수를 선언할 수 있다. (모든 경우에 사용할수 X)

화살표 함수의호출

화살표함수는 익명함수로만 사용할수 있어서 호출하기 위해서는 함수표현식을 사용한다.

매개변수 지정 방법

() => {...} 매개변수가 없을 경우
x => {...} 매개변수가 한개인경우, 소괄호 생략 가능
(x,y) => {...} 매개변수가 여러개인 경우, 소괄호 생략할수 없음

함수몸체 지정 방법
x => { return xx } single line block
x => x
x
함수 몸체가 한줄의 구문이라면, 중괄호를 생략할 수 없으며, 암묵적으로 return된다.

    () => { return { a: 1 }; }
    () => ({ a: 1 })

    () => {  //multi line block
        const x = 10;
        return x*x;
    };
<script>
	//ES5
    var pow1 = function(x) { return x*x; };
    console.log(pow1(10)); //100

    //ES6
    const pow = x => x*x;
    console.log(pow(10)); //100

    //ES5
    var arr = [1,2,3];
    var poww = arr.map( function(x){
        return x*x;
    });
    console.log(poww); // [1,4,9]

    //ES6
    const poo = x => x*x;
    console.log(poo(10)); //100

    //ES5
    var ree = [1,2,3];
    var pee = ree.map( function(x){
        return x*x;
    });
    console.log(pee); // [1,4,9]

    //ES6
    const reee = [1,2,3];
    const peee = reee.map(x=>x*x);
    console.log(peee);  // [1,4,9]
</script>

일반함수의 this

-일반 함수의 경우, 해당 함수를 호출하는 패턴에 따라
this에 바인딩되는 객체가 달라지고, 콜백함수 내부의 ,this는 전역객체 window를 가르킨다.

<script>
	function Prefixer(prefix){
        this.prefix = prefix;
    }
    Prefixer.prototype.prefixArray = function(arr){
        //(A)
        return arr.map( function(x){
            return this.prefix + ' ' + x; //(B)
        });
    };
    
    var pre = new Prefixer('Hi');
    console.log(pre.prefixArray(['Lee','kim'])); 
</script>

(A)지점에서의 this는 생성자함수 Prefixer가 생성한 객체,
생성자 함수의인스턴스 (위예제의 경우 pre).

(B)지점에서 사용한 this는 전역객체 window를 가르킨다.
생성자함수와 객체의 메소드를 제외한 모든 함수 내부의 this는 전역객체를 가르키기 때문

((A)처럼 pre라고 생각하겠지만)..

.
.
.

넘 어렵다..😢 다시 소화시키고 수정하겠다..

profile
Web publisher

0개의 댓글