Skip to main content

Command Palette

Search for a command to run...

[TIL] JS HWs & Part 4, 5 Concept: Callback function, Class, and Closure

04/05/23

Updated
[TIL] JS HWs & Part 4, 5 Concept: Callback function, Class, and Closure

JS Part 3 HW

HW 1

// When the code is executed, print "Passed ~ " by writing getAged()

var user = {
    name: "john",
    age: 20,
};

var getAged = function (user, passedTime) { // shallow copy
    var user2 = {}
    for (var prop in user) {
        user2[prop] = user[prop];
    }
    user2.age += passedTime
    return user2
};

var agedUser = getAged(user, 6);

var agedUserMustBeDifferentFromUser = function (user1, user2) {
    if (!user2) {
        console.log("Failed! user2 doesn't exist!");
    } else if (user1 !== user2) {
        console.log(
            "Passed! If you become older, you will be different from you in the past!"
        );
    } else {
        console.log("Failed! User same with past one");
    }
};

agedUserMustBeDifferentFromUser(user, agedUser);

HW2

Explain the reason why the following result is printed

fighter.opponent.getFullname(): 첫번째 줄 Francis Ngannou가 출력된 이유는 getFullname()이 opponent의 메서드로서 실행이 되는데 이떄 this가 가리키는 것이 자신을 부른 주체가 되기 때문에 opponent가 되고 그 opponent의 fullname이 해당 이름이기 때문이다

fighter.getName(): 첫번째 줄 VS 다음에 John Jones가 출력된 이유는 getName()이 fighter의 메서드로서 실행이 되는데 이때 this가 가리키는 것은 위의 이유와 마찬가지로 fighter이고 이 fighter의 fullname이 해당 이름이기 때문이다

fighter.getName(): 두번째 줄 John Jones가 출력된 이유는 첫번째 줄 VS 다음에 John Jones가 출력된 이유와 동일하다

fighter.getFirstName(): 두번째 줄 VS 다음 Ciryl이 출력된 이유는 먼저 getFirstName()은 일반 함수가 아닌 화살표 함수이므로 this binding 과정이 일어나지 않아서 fullname은 글로벌로 선언이 된 Ciryl Gane이 되고 split을 통해 firstname인 Ciryl만 출력하게 된다

fighter.getLastName: 두번째 줄 Cityl 다음 Gane이 출력된 이유는 클로저가 사용되어 호출의 주체가 없이 그냥 괄호 안의 함수를 실행시키는 것이어서 (즉시 실행 함수) 글로벌로 선언된 fullname이 해당되고 lastname만이 출력된다

JS Concept Lecture Note Taking

JS Part 4 HW

  • Refactoring code with async/await
function loadJson(url) {
  return fetch(url)
    .then(response => { // need to remove .then
      if (response.status == 200) {
        return response.json();
      } else {
        throw new HttpError(response);
      }
    })
}

function narutoIsNotOtaku() {
  let title = prompt("Enter the title of anime.", "naruto");

    return loadJson(`https://animechan.vercel.app/api/random/anime?title=${title}`)
    .then(res => { // need to remove .then
            alert(`${res.character}: ${res.quote}.`);
      return res;
    })
    .catch(err => { // instead of .catch(), use try {} catch {}
      if (err instanceof HttpError && err.response.status == 404) {
        alert("No anime found. If you are not a otaku, just enter naruto, onepiece!");
        return narutoIsNotOtaku();
      } else {
        throw err;
      }
    });
}
// Refactoring
let loadJson = async (url) => {
    let response = await fetch(url); // instead of .then, use await
    if (response.status == 200) { // execute when await is done
        return response.json();
    } else {
        throw new HttpError(response);
    }
}

let narutoIsNotOtaku = async () => {
    let title, res;

    // while: wait until the user enters something in the prompt
    while (1) {
        title = prompt("Enter the title of anime.", "naruto");
        try {
            res = await loadJson(
                `https://animechan.vercel.app/api/random/anime?title=${title}`
            ); // wait until fetch API
            break; // break out of while loop
        } catch (err) { 
            if (err instanceof HttpError && err.response.status == 404) {
                alert(
                    "No anime found. If you are not a otaku, just enter naruto, onepiece!"
                );
                return narutoIsNotOtaku();
            } else {
                throw err;
            }
        }
    }
    alert(`${res.character}: ${res.quote}.`);
    return res; // async function always return Promise
}

JS Part 5 HW

  • Add Promise code to the program
async function makeAnswerCircle(guess) {
    const CIRCLE_NAME = "answer";
    // after showCircle function's task is done, add answerCircle as id inside div and add the name of circle
    let div = await showCircle(guess, CIRCLE_NAME, $answerCircleArea);
    div.id = "answerCircle";
    div.innerHTML = CIRCLE_NAME;
}

async function makeGuessCircle(guess) {
    const CIRCLE_NAME = "guess";
    // after showCircle function's task is done, add guessCircle as id inside div and add the name of circle
    let div = await showCircle(guess, CIRCLE_NAME, $guessCircleArea);
    div.id = "guessCircle";
    div.innerHTML = CIRCLE_NAME;
}

Today I Learned

Part 1 of 50

Today I Learned!