this is the object that the function is a property of
어떤 객체가 있고 객체에 함수 프로퍼티가 있다. 함수에서 this는 그 함수가 있는 객체를 가리킨다.
obj.someFunc(this)
function a() {
console.log(this)
}
a()
//window.a()
function b() {
'use strict'
console.log(this)
}
b()
//undefined
const obj = {
name: 'Billy',
sing: function() {
return 'lalala' + ...
}
}
obj 객체의 함수 sing은 name프로퍼티 값을 가지고 오고 싶으면 어떻게 해야될까?
const obj = {
name: 'Billy',
sing: function() {
return 'lalala' + this.name
}
}
obj.sing()
obj.sing()
this는 '.'을 기준으로 왼쪽을 가리킨다
const obj = {
name: 'Billy',
sing() {
return 'lalala' + this.name
},
singAgain() {
return 'lalala' + this.name + '!'
}
}
obj.singAgain()
const obj = {
name: 'Billy',
sing() {
return 'lalala' + this.name
},
singAgain() {
return this.sing() + '!'
}
}
obj.singAgain()
함수가 객체의 다른 프로퍼티를 쓸 수 있게된다.
같은 코드를 다중의 객체에서 쓸 수 있다.
function importantPerson() {
cosnole.log(this.name)
//this = Window 객체
}
importantPerson()
//window.importantPerson()
const name ='Sunny'
const obj1 = {
name : 'Cassy',
importantPersone: importantPerson()
//this.name: 'Cassy'
}
const obj2 = {
name : 'Jacob',
importantPersone: importantPerson()
//this.name: 'Jacob'
}
const a = function() {
console.log('a', this)
const b = function () {
console.log('b', this)
const c = {
hi: function() {
console.log('c', this)
}
}
c.hi()
}
b()
}
// a Window
// b Window Window.a(b()) : this는 '.'을 기준으로 왼쪽
// c {hi: f}
const obj = {
name: 'Billy',
sing() {
console.log('a', this);
var anothreFunc = functino() {
console.log('b', this)
}
anotherFunc()
}
}
obj.sing()
// a {name: 'Billy', sing: f}
// b Window
const obj = {
name: 'Billy',
sing() {
console.log('a', this);
var anothreFunc = () => {
console.log('b', this)
}
anotherFunc()
}
}
//obj.sing()
// a {name: 'Billy', sing: f}
// b {name: 'Billy', sing: f}