JavaScipt 에서의 This 예시

김재민·2023년 5월 26일
0

1.일반 함수에서 호출시 (전역 객체)

console.log(this === window); // true

a = "KJM";
console.log(window.a); // KJM

function x(){
  return this;
}

x() === window; // true

2.메서드 에서 호출시(호출한 객체)

let fruit = {
    favorite: "apple",
    lestFaverite: "orange",
    favoriteFruit() {
        console.log(this.favorite + "is my favorite fruit")
    }
}

fruit.favoriteFruit(); // apple is my favorite fruit

3. 생성자 함수에서 호출시(생성자 함수가 생성할 객체)

function Fruit() {
    this.favorite = "apple",
    this.lestFaverite = "orange",
    this.start = function() {
        console.log(this.favorite + "is my favorite fruit")
    }
}

let Fruit = new fruit();

console.log(person1); // { favorite: 'apple', lestFaverite: 'orange', start: [Function] }

0개의 댓글