What this refers to in JavaScript: functions, methods, and new
1. Called as a regular function
js
function a() {
console.log(this);
return ;
}
a(); // windowWhen you just call a function, the value of this refers to the global object (window).
2. Called as a method
- A method is a function inside an object. This is the case where you call the function with a . attached, in the form objectName.functionName.
js
const obj = {
func() {
console.log(this);
return ;
},
sub: {
subFunc() {
console.log(this);
return ;
}
}
}
obj.func(); // (1) obj
obj.sub.subFunc(); // (2) sub3. apply/ call / bind
- apply/call/bind are methods that let the developer explicitly set the value of this to the object they want.
4. The new operator - constructor functions
js
function Person(name,age) {
this.name = name,
this.age = age,
// note that there is no return statement
}
function PersonReturn(name, age) {
this.name = name,
this.age = age,
return {
name: "고릴라",
age: 13
}
}
const 영희 = new Person("영희", 23); // (1)
const 의섭 = new Person("의섭", 26); // (2)
const 고릴라 = new PersonReturn("원숭이", 31);
console.log(고릴라.name); // 고릴라- this is decided when the function is called
- Used in the global scope, this points to the global object
- Used in a function, it also points to the global object
- Used in a method that belongs to an object, it points to that method's object (the object written before the dot)
- Used in an inner function of a method that belongs to an object, it points to the global object
- Used in a constructor, it points to the new object created by the constructor
Source: https://amyhyemi.tistory.com/224
https://velog.io/@uiseop/this%EC%9A%A9%EB%B2%95%EC%97%90-%EB%8C%80%ED%95%B4%EC%84%9C
- #frontend developer Sungjun Um
- #Zerobase
- #Autowini
- #frontend
- #Zerobase Frontend School
- #frontend developer
- #Programmers
- #Vite
- #Number()
- #sort()
- #WiniLogis
- #frontend school
- #String()
- #forEach()
- #join()
- #React
- #Next.js
- #split()