일반함수
constructor
를 내장 (constructor는 들어있는 게 많아서 무거움)
객체의 메서드
로 많이 사용 (this를 찾기 위해)
- 일반함수에서 사용하는
this
: 나를 호출한 대상을 찾음
다양한 예시
function func() {
console.log(this);
}
func();
let newJeans = {
name: '민지',
age: 20,
sayHi: function () {
console.log(this);
}
}
newJeans.sayHi();
let newJeans = {
name: '민지',
age: 20,
sayHi: {
hello: function () {
console.log(this);
}
}
}
newJeans.sayHi.hello();
let newJeans = {
name: '민지',
age: 20,
sayHi: function () {
console.log(this);
function hello() {
console.log(this);
}
hello();
}
}
newJeans.sayHi();
📍주의)
스코프, 괄호로 감싸준 대상이 아닌 호출한 대상을 찾음.
그래서 호출한 대상이 없으면 전역객체인 Window 반환
화살표함수 (Arrow function)
constructor
를 내장하지 않음
메서드 안의 함수
로 많이 사용 (상위 this를 가져오기 위해)
- 화살표 함수에서 사용하는
this
: 자체를 바인딩(가지지) 않음
부모나 상위요소가 사용한 this 값을 그대로 사용
(일단 주변에서 찾고 없으면 상위로 감. 그래서 제일 상위인 Window를 찾아가기도 함)
다양한 예시
let func = () => {
console.log(this);
}
func();
let newJeans = {
name: '민지',
age: 20,
sayHi: () => {
console.log(this);
}
}
newJeans.sayHi();
let newJeans = {
name: '민지',
age: 20,
sayHi: {
hello: () => {
console.log(this);
}
}
}
newJeans.sayHi.hello();
let newJeans = {
name: '민지',
age: 20,
sayHi: () => {
console.log(this);
function hello() {
console.log(this);
}
hello();
}
}
newJeans.sayHi();
let newJeans = {
name: '민지',
age: 20,
sayHi: () => {
console.log(this);
let hello = () => {
console.log(this);
}
hello();
}
}
newJeans.sayHi();
let newJeans = {
name: '민지',
age: 20,
sayHi: function () {
console.log(this);
let hello = () => {
console.log(this);
}
hello();
}
}
newJeans.sayHi();
let newJeans = {
name: '민지',
total: 0,
num: [10, 20, 30, 40, 50],
numTotal: function () {
this.num.forEach(function (item) {
this.total += item;
})
return this.total;
}
}
console.log(newJeans.numTotal());
let newJeans = {
name: '민지',
total: 0,
num: [10, 20, 30, 40, 50],
numTotal: function () {
this.num.forEach((item) => {
this.total += item;
})
return this.total;
}
}
console.log(newJeans.numTotal());
축약된 메서드 (Concise Method)
- ES6 신문법
- 코드 작성 시
: function
생략
constructor
를 내장하지 않음
- Concise Method에서 사용하는
this
: 일반함수처럼 나를 호출한 대상을 찾음
const std = {
name : 'song',
num : 20231205,
sayHi(){
console.log(`안녕, 나는 ${this.name}라고 해`);
}
}