setTimeOut이나 setInterval 같은 함수 사용시 콜백으로 화살표함수 사용하는것이 더 활용서이 뛰어나다
//this 일반함수, 화살표함수 차이
//일반(normal) 함수는 호출 위치에 따라 this 정의 !!
//화살표(arrow) 함수는 자신이 선언된 함수 범위 내에서 this 정의 !!
function User(name){
this.name = name;
}
User.prototype.normal = function(){
console.log(this.name);
}
User.prototype.arrow = () => {
console.log(this.name);
}
//객체생성자함수
const mag = new User('phter');
mag.normal(); //pheter
mag.arrow();// undefined
//***화살표함수의 this 활용
const timer = {
name:'minji',
timeout:function(){
setTimeout(()=>{
console.log(this.name);
//function(){ console.log(this.name)}; //setTimeout 위치 내에서 this가 없으므로 udefined
},2000)
}
}
timer.timeout(); //2초뒤 실행
'프론트엔드 공부 > javscript' 카테고리의 다른 글
String prototype - indexOf,length,slice,replace,match,trim (0) | 2021.05.21 |
---|---|
class 상속과 확장 (0) | 2021.05.21 |
변수유효범위(variable scope) (0) | 2021.05.20 |
객체불러오기(펼침연산자사용>복사,추가,결합) (0) | 2021.05.06 |
객체불러오기(변수,forin,map) (0) | 2021.05.06 |