바닐라 자바스크립트 퀴즈
문제 1
function Cat(name, age){
this.name = name; // this가 윈도우를 가르킨다
this.age = age;
}
const tabby1 = Cat('nana', 7); // new를 붙여주면 this는 새로 생긴 객체를 가르킨다
console.log(tabby1.name); //error 발생
console.log(window.name); //'nana'
문제 2
(function(name) {
console.log(`hello ${name}`); // 변수가 함수에 묶이고 window를 침범하지 않아 전역이 깨끗해진다
})('Baek'); // 'hello Baek'이 출력된다
const logger = (function(){
//logCount는 밖에서 접근할 수 없다. 일종의 private 효과
let logCount = 0;
function log(message) {
console.log(message);
logCount = logCount + 1;
}
function getLogCount() {
return logCount;
}
return {
log: log,
getLogCount: getLogCount
}
})()
문제 3
var idiots = {
name: 'idiots',
genre: 'punk rock',
members: {
roto: {
memberName: 'roto',
play: function() {
console.log(`band ${this.name} ${this.memberName} play start`);
//객체 내에 memberName은 있지만 name은 없어서 band undefined roto play start가 된다
// this.name이 아니라 idiots.name을 사용하면 된다
}
}
}
}
idiots.members.roto.play();
var thisTest = {
whoAmI : function() {
console.log(this);
},
testInTest: {
whoAmI: function() {
console.log(this);
}
}
}
문제 4
setTimeout 내의 function의 this는 RockBand의 this를 가리키지 않기 때문에 오류가 발생한다
function RockBand(members) {
this.members = members;
this.perform = function () {
setTimeout(function () {
this.members.forEach(function (member) {
member.perform();
});
}, 1000); // setTimeout(function, 1000) > 1초 뒤에 함수 실행
};
}
var theOralCigarettes = new RockBand([
{
name: "takuya",
perform: function () {
console.log("Sing: a e u i a e u i");
},
},
]);
theOralCigarettes.perform();
해결 1. arrow function(자체 스코프를 가지고 있지 않다)
function RockBand(members) {
this.members = members;
this.perform = function () {
setTimeout(() => {
this.members.forEach(function(member) {
member.perform();
});
}, 1000);
};
}
해결 2. bind 사용
function RockBand(members) {
this.members = members;
this.perform = function() {
setTimeout(function() {
this.members.forEach(function(member){
//this가 rockband의 this를 카리키지 않음
member.perform();
})
}.bind(this), 1000)
}
}
해결 3. 클로져 사용 (this를 다른 변수에 넣어서)
function RockBand(members) {
var that = this;
this.members = members;
this.perform = function() {
setTimeout(function() {
that.members.forEach(function(member){
//this가 rockband의 this를 카리키지 않음
member.perform();
})
}, 1000)
}
}
문제 5
setTimeout 이후 참조한 i는 이미 for 루프가 끝난 이후의 i이기 때문에 항상 5 그렇게 때문에 numbers[5]는 undefined
const numbers = [0, 1, 2, 3, 4];
for(var i=0; i < numbers.length; i++) {
setTimeout(function(){
console.log(`[${i}] number ${numbers[i]} turn!`);
}, i * 1000)
}
해결 1. IIFE(i가 0일떄, 1일때, 2일때, 3일때, 4일때를 각각의 function scope로 가두어서 처리)
for(var i=0; i < numbers.length; i++) {
(function(index) {
setTimeout(function(){
console.log(`[${index}] number ${numbers[i]} turn!`);
}, i * 1000)
})(i)
}
해결 2. var 대신 let 쓰기
for(let i=0; i < numbers.length; i++) {
setTimeout(function(){
console.log(`[${i}] number ${numbers[i]} turn!`);
}, i * 1000)
}
해결 3. for 대신 forEach 쓰기(각각 function을 만들어 i의 값이 고유해짐)
numbers.forEach(function(number, i) {
setTimeout(() => {
console.log(`[${i}] number ${number} turn!`);
}, i * 1000)
})
문제 6. var, let, const의 차이는 무엇인가요?
var : function scope, 변수 재할당 가능, 호이스팅이 일어남(function scope상 맨 위로 var선언이 끌어올려진다)
let : block scope, 변수 재할당 가능
const : block scope, 변수 재할당 불가능
문제 7. 클로져는 무엇인가요?
'👨💻 TIL' 카테고리의 다른 글
TIL12 - 2023.10.06 (1) | 2023.10.07 |
---|---|
TIL11 - 2023.10.05 (0) | 2023.10.06 |
TIL9 - 2023.10.03 (1) | 2023.10.04 |
TIL8 - 2023.10.02 (0) | 2023.10.02 |
TIL7 - 2023.09.27 (0) | 2023.09.27 |