자바 스크립트에서 "이것"이란 무엇입니까?
2458 단어 javascriptthis
this
키워드가 다양한 조건에서 무엇을 참조하는지 탐구하고 거기에서 키워드와 자바스크립트에서 어떻게 작동하는지 이해합니다.this
키워드는 다음을 가리킬 수 있습니다.window
객체 - 함수 내에서 참조되는 경우. 객체의 메서드 내에서 - 화살표 기능 없음
```javascript const obj = { name: "obj", printName() { console.log(this.name); }, printObj() { console.log(this); } } obj.printName(); // obj obj.printObj(); // {name: "obj", printName: ƒ, printObj: ƒ} ```
this 내에서 객체의 메서드 - 화살표 함수
화살표 함수에서
this
값은 항상 부모가 아닌 화살표 함수에서 this
값입니다.```javascript const obj = { name: "obj", printObj: () => { console.log(this); // this refers to the window } } obj.printObj() // Window {window: Window, self: Window, document: document, name: "", location: Location, …} ```
이것은 함수 본문 내에서
```javascript function greet() { console.log(this); } greet(); // Window {window: Window, self: Window, document: document, name: "", location: Location, …} ```
이것은 new 키워드가 사용될 때
```javascript function Game(inTitle) { this.title = inTitle; console.log(this); // Game {title: "pong"} } const game = new Game("pong"); ```
이것은 객체 메소드의 콜백 내 - 화살표 기능 없음
```javascript const fruits = { name: "fruits", fruits: ["apple", "mango", "banana"], printFruits() { console.log(this); // {name: "fruits", fruits: Array(3), printFruits: ƒ} this.fruits.forEach(function(fruit) { console.log(this); // Window {window: Window, self: Window, document: document, name: "", location: Location, …} * 3 times }) } } fruits.printFruits(); ```
객체의 메소드에서 콜백 내 this - 화살표 함수
```javascript const fruits = { name: "fruits", fruits: ["apple", "mango", "banana"], printFruits() { console.log(this); // {name: "fruits", fruits: Array(3), printFruits: ƒ} this.fruits.forEach((fruit) => { console.log(this); // {name: "fruits", fruits: Array(3), printFruits: ƒ} * 3 times }) } } fruits.printFruits(); ```
Reference
이 문제에 관하여(자바 스크립트에서 "이것"이란 무엇입니까?), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/rakshithbellare/what-is-this-in-javascript-4dhp텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)