[SEB_FE]Javascript-Koans

따봉도치 개발자·2023년 3월 6일
1
post-thumbnail

Koans

Koans란 불교에서 유래된 단어로, 결론을 내리기 전에 이게 왜 맞는지 깊게 고민한다는 의미를 가지고 있다고 한다.

몰랐던 거

  1. this
  2. arguments
  3. 08_Object의 주석 부분
  4. 09_SpreadSyntax의 주석 부분

1. this

  • 함수 안에서 쓸 때 - 함수 주인에게 바인딩
function myFunction() {
  return this;
}
console.log(myFunction()); //Window
다만, strict mode(엄격 모드)에서는 조금 다르다.
함수 내의 this에 디폴트 바인딩이 없기 때문에 undefined가 됩니다.
  • 객체 안에서 쓸 때 - 메서드 내부 코드에서 사용된 this는 해당 메서드를 호출한 객체로 바인딩된다.
  firstName: 'John',
  lastName: 'Doe',
  fullName: function () {
    return this.firstName + ' ' + this.lastName;
  },
};
 person.fullName(); //"John Doe"

2. arguments

arguments는 자바스크립트 함수 내에서 사용되는 지역 변수이다. 이 변수는 함수를 호출할 때 전달된 인자들을 배열 형태로 저장하고 이 배열은 함수 내에서 arguments라는 이름으로 사용된다. 예시를 보자.

  let result = 0;
  for (let i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}
sum(1, 2, 3); // 6
sum(1, 2, 3, 4, 5); // 15

이 함수는 호출할 때 전달된 모든 인자들의 합을 계산하여 반환한다. 이때, arguments를 사용하여 함수가 호출될 때 전달된 모든 인자들을 합산할 수 있다.
따라서, arguments는 함수 내에서 가변적인 인자를 다루는 데 유용하게 사용된다.

3. 08_Object

const megalomaniac = {
  mastermind: 'Joker',
  henchwoman: 'Harley',
  getMembers: function () {
    return [this.mastermind, this.henchwoman];
  },
  relations: ['Anarky', 'Duela Dent', 'Lucy'],
  twins: {
    'Jared Leto': 'Suicide Squad',
    'Joaquin Phoenix': 'Joker',
    'Heath Ledger': 'The Dark Knight',
    'Jack Nicholson': 'Tim Burton Batman',
  },
};console.log(megalomaniac.length); // undefined
//! 함수 객체의 length를 구하고 싶으면 key의 length를 하면 된다!
let keys =  Object.keys(megalomaniac).length;
console.log(keys);
  • 외부 객체내부 객체를 복사했을 때 복사의 깊이
      const obj = {
        mastermind: 'Joker',
        henchwoman: 'Harley',
        relations: ['Anarky', 'Duela Dent', 'Lucy'],
        twins: {
          'Jared Leto': 'Suicide Squad',
          'Joaquin Phoenix': 'Joker',
          'Heath Ledger': 'The Dark Knight',
          'Jack Nicholson': 'Tim Burton Batman',
        },
      };
      function passedByReference(refObj) {
        refObj.henchwoman = 'Adam West';
      }
      passedByReference(obj);
      expect(obj.henchwoman).to.equal('Adam West');
      const assignedObj = obj;
      assignedObj['relations'] = [1, 2, 3];
      expect(obj['relations']).to.deep.equal([1,2,3]);
      const copiedObj = Object.assign({}, obj);
      copiedObj.mastermind = 'James Wood';
      expect(obj.mastermind).to.equal("Joker"); 
      obj.henchwoman = 'Harley';
      expect(copiedObj.henchwoman).to.equal("Adam West");
      delete obj.twins['Jared Leto'];
      expect('Jared Leto' in copiedObj.twins).to.equal(false);
      // obj.twins와 copiedObj.twins의 주소값이 달라서 obj.twins를 
      	delete를 해도 copiedObj.twins는 변하지 않나?
      // 객체는 서로 다른 주소를 참조하고 있어 깊은 복사가 이루어졌지만 
     	내부의 객체는 같은 주소를 참조하고 있다.

09_SpreadSyntax

function getAllParamsByArgumentsObj() {
      return arguments;
    }
    const restParams = getAllParamsByRestParameter('first', 'second', 'third');
    const argumentsObj = getAllParamsByArgumentsObj('first', 'second', 'third');
 		expect(Object.keys(argumentsObj)).to.deep.equal(["0","1","2"]); 
    	// key값은 인덱스 
  	const argsArr = Array.from(argumentsObj);
    	expect(argsArr === restParams).to.deep.equal(false);  
    	// 주소값이 다른거네?
  });

누군가가 성의없이 썼다고 핀잔을 줘서 수정한다... 내가 봐도 좀 글앴다..

profile
Explain Like I'm 5

1개의 댓글

comment-user-thumbnail
2023년 3월 7일

엄청난 발전이네요 !!

답글 달기