2022년 12월 5일 월요일

[Javascript] call, apply, bind

JS에서는 함수 호출 방식과 관계없이 this를 지정할 수 있음


const mike = {

    name: 'Mike',

};


const tom = {

    name: 'Tom',

}


function showThisName() {

    console.log(this.name);

}


showThisName();    // 아무것도 나오지 않음

showThisName.call(mike);    // Mike

showThisName.call(tom);    // Tom

// 함수.call()의 인자로 객체를 넘기면 this에 할당됨


function update(birthYear, occupation) {

    this.birthYear = birthYear;

    this.occupation = occupation;

}


update.call(mike, 1999, 'singer');

update.call(tom, 2002, 'teacher');


update.apply(mike, [1999, 'singer']);

update.apply(tom, [2002, 'teacher']);


const updateMike = update.bind(mike);

// mike 객체가 할당되어 update기능을 수행하는 updateMike라는 함수를 만듦


[Javascript] Number, Math

Number

toString()

: 10진수 -> 2진수/16진수


let num = 10;

num.toString();    // '10'

num.toString(2);    // '1010'

let num2 = 255;

num2.toString(16);    // 'ff'


toFixed()

: 소수점 자릿수


let userRate = 30.1234;

userRate.toFixed(2);    // '30.12'

userRate.toFixed(0);    // '30'

userRate.toFixed(6);    // '30.123400'

Number(userRate.toFixed(2);    // 30.12


Math

Math.PI;    // 3.141592653589793


Math.ceil();    // 올림

Math.floor();    // 내림

Math.round();    // 반올림


Math.random();    // 0 ~ 1 사이 무작위 숫자 생성

Math.abs(n);    // n의 절대값

Math.pow(n, m);    // n의 m 거듭 제곱 값

Math.sqrt(n);    // n의 제곱근


기능함수들

isNaN()

: NaN인지 아닌지 구분


parseInt()

: 숫자로 변경

let margin = '10px';
parseInt(margin);    // 10 -> 문자가 나올때까지의 숫자를 변경
Number(margin);    // NaN

let redColor = 'f3';
parseInt(redColor);    // NaN
parseInt(redColor, 16);    // 243 -> 16진수 문자열 redColor를 10진수로 변경

parseInt('11', 2);    // 3 -> 2진수 문자열 '11'을 10진수로 변경


parseFloat()

: 부동소수점으로 변환