Javascript/객체
Javascript 객체 안에 함수 넣는방법 feat.화살표함수
컴공 윤서혜 학습일기
2021. 1. 31. 16:22
총 3가지 방법이 있습니다.
1. say: function say()
const dog = {
name: "멍멍이",
sound: "멍멍!",
say: function say() {
console.log(this.sound);
}
};
dog.say();
2. say: function ()
const dog = {
name: "멍멍이",
sound: "멍멍!",
say: function() {
console.log(this.sound);
}
};
dog.say();
3. say()
const dog = {
name: "멍멍이",
sound: "멍멍!",
say() {
console.log(this.sound);
}
};
dog.say();
**주의점!** 화살표함수를 사용하면 작동이 되지 않습니다.
const dog = {
name: "멍멍이",
sound: "멍멍!",
say: ()=> {
console.log(this.sound);
}
};
dog.say();
//출력값
TypeError: Cannot read property 'sound' of undefined
function 키워드들은 자신이 속해있는곳을 가리키게 되는데, 화살표함수는 this를 자신이 속해있는곳으로 연결하지 않습니다.