Default Value를 지정하는 방법은 알고 있었지만, 함수를 넘김으로서 에러처리를 할 수 있다는 것은 처음 알았다.
예시를 보자
function Person ({name='Tom',age}){
this.name = name;
this.age = age;
}
const Inkyu = new Person({name:'Inkyu',age:20});
console.log(Inkyu) // {name:'Inkyu',age:20}
const noName = new Person({age:30})
console.log(noName) // {name:'Tom',age:30}
Default value를 지정해주면, 실제로 그 값이 들어오지 않더라도 지정해 준 값으로 생성자 함수를 실행하는 것을 볼 수 있다.
만약, Default value를 지정해 주지 않고 인자를 넘기면 어떻게 될까?
function Person ({name,age}){
this.name = name;
this.age = age;
}
const noName = new Person({age:30});
console.log(noName) // {name:undefined,age:30}
보다시피 오류가 발생하는 것이 아닌 undefined가 할당된다.
강의에서는 인자 관리를 조금 더 안전하게 하기 위해, 인자가 들어오지 않는 경우 에러를 내는 함수를 작성하여, Default value로 주었다.
const required = (argName) =>{
throw new Error(`${argName} 인자가 없습니다`);
}
function Person ({name=required('name'),age=required('age')}){
this.name = name;
this.age = age;
}
const noName = new Person({age:30}) // name 인자가 없습니다.
보통 js에 대해서 공부를 하면 this
라는 키워드와 마주치게 된다.
this
는 자신을 호출한 객체에 대한 정보를 가지고 있는데, 함수의 호출 방식에 따라 다른 값을 가진다.
1. 일반 함수
this는 전역 객체를 가리킨다. 브라우저 환경에서는 window를, Node환경에서는 global 객체를 가리킨다. 왜냐하면, 내가 함수를 작성하면, window 객체의 property로 등록되는 것과 마찬가지이다.
function whereThis(){
console.log(this) // window {...} || global {...}
}
// whereThis는 window 객체의 property 이므로 다음과 같은 코드도 동작한다.
window.whereThis() // window {...}
2. 메소드
메소드는 객체에 의존적이기 때문에, this는 메소드를 호출하고 있는 대상을 가리킨다. 이는 call, apply... 등 호출 대상을 바꿀 수 있는 경우에도 그대로 적용된다.
const whereThis = {
printThis(){
console.log(this)
}
}
whereThis.printThis(); // {printThis: f ...}
//call을 이용하여 메소드를 호출하는 주체가 변경되었을 때
const person = {
name:'inkyu',
age: 20
}
whereThis.printThis.call(person) // {name : 'inkyu' , age:20 }
3. 생성자 함수
생성자 함수는 함수와 다르게 동작한다.
function Person (name,age){
//this = {};
this.name = name // this = {name : ~}
this.age = age // this = {name: ~ , age: ~}
//return this
}
화살표 함수에는 this binding이 없다. 즉 자신을 호출한 대상에 대한 정보가 존재하지 않는다. 따라서 자신의 상위 스코프를 돌아다니면서, this binding에 대한 정보를 찾게 된다.
this나 super에 대한 바인딩이 없고, methods 로 사용될 수 없습니다. (MDN)
왜 method로 사용을 못하는걸까?
만약 화살표 함수를 부른 객체에 의존적인 작업을 하기 위해서 this를 사용한다면...? 예상치 못한 결과를 초래한다.
const person = { name : 'abc' ,
age : 20 ,
// 나는 누가 호출했는지에 대한 정보를 몰라요~
printThis : () => console.log(this)
}
person.printThis() // window {...}
근데 왜 window를 내뱉는 걸까? 사실 person의 정체는...!
window.person.printThis()
따라서 person에 대한 정보가 없으니, 그보다 상위 스코프에 있는 window 객체를 결과로 내뱉는다.
의문점 - 위와 같은 경우, person을
var
키워드로 선언하면, window 객체의 property로 person이 존재하는 것을 볼 수 있지만,
const
와let
은 window 객체의 property로 직접 등록되지 않음에도, 같은 결과를 보여준다. 이유를 찾으면 수정해보자...
스코프 체인 타고 올라가다 보면, 상위에는 항상 전역 객체가 있어서가 아닐까...
중첩된 함수의 경우에는 다음과도 같이 동작한다.
const person = { name : 'inkyu',
age : 20,
outerPrintThis() {
console.log(this)
const innerPrintThis = () => console.log('inner this : ' , this)
innerPrintThis()
}
}
person.outerPrintThis() // {name:'inkyu...} , inner this : {name:'inkyu...}