반응형
let newArr1 = [1,2,3,4,5].map(function(v, i, o){
return v * 2;
})
console.log(newArr1);
let newArr2 = [1,2,3,4,5].map((v, i, o) => v * 3 );
console.log(newArr2);
this context
const myObj = {
runTimeout(){
setTimeout(function(){
this.printData();
}, 200)
},
printData(){
console.log('hihi');
}
}
myObj.runTimeout(); // error
1.
const myObj = {
runTimeout(){
setTimeout(function(){
this.printData();
}.bind(this), 200)
},
printData(){
console.log('hihi');
}
}
myObj.runTimeout(); // hihi
2.
const myObj = {
runTimeout(){
setTimeout(() => {
this.printData();
}, 200)
},
printData(){
console.log('hihi');
}
}
myObj.runTimeout(); //hihi
1. bind(this)를 통해서 this를 찾아준다.
2. arrow function의 경우 this가 window가 아닌 context를 바라보게 된다.
default parameters
function sum(value, size){
return value * size;
}
console.log(sum(3)); // NaN
1.
function sum(value, size){
size = size || 1;
return value * size;
}
console.log(sum(3)); // 3
2.
function sum(value, size=1){
return value * size;
}
console.log(sum(3)); // 3
3.
function sum(value, size={value:1}){
return value * size.value;
}
console.log(sum(3, {value:30})); // 90
rest parameter
function checkNum(){
const argArray = Array.prototype.slice.call(arguments);
console.log(argArray); // [10, 2, 3, 4, 5, '66']
}
const result = checkNum(10, 2, 3, 4, 5, '66');
function checkNum(){
const argArray = Array.prototype.slice.call(arguments);
console.log(argArray);
const result = argArray.every((v) => typeof v === 'number');
console.log(result); // false
}
const result = checkNum(10, 2, 3, 4, 5, '66');
function checkNum(...argArray){
console.log(toString.call(argArray));
console.log(argArray);
const result = argArray.every((v) => typeof v === 'number');
console.log(result); // false
}
const result = checkNum(10, 2, 3, 4, 5, '66');
위와 같이 매개변수에 ...으로 들어간다면 값을 배열로 받는 것이다.
반응형
'인강 > 모던 자바스크립트(javascript) 개발을 위한 ES6 강좌' 카테고리의 다른 글
Class (0) | 2023.01.26 |
---|---|
Template (0) | 2023.01.26 |
Set (0) | 2023.01.24 |
Obj (0) | 2023.01.24 |
Array (0) | 2023.01.24 |