kgneng2 / blokg

blog
MIT License
0 stars 0 forks source link

Javascript 'This' #23

Open kgneng2 opened 4 years ago

kgneng2 commented 4 years ago

This 는 현재 실행 문맥이다

function nonStrictMode() {
  return this
}

function strictMode() {
  'use strict'
  return this
}

console.log(nonStrictMode()) // window
console.log(strictMode()) // undefined
console.log(window.stricMode()) // window

생성자 함수/ 객체

function NewObject(name, color) {
  this.name = name
  this.color = color
  this.isWindow = function() {
    return this === window
  }
}

const newObj = new NewObject('nana', 'yellow')
console.log(newObj.name) // nana
console.log(newObj.color) // yellow
console.log(newObj.isWindow()) // false

const newObj2 = new NewObject('didi', 'red')
console.log(newObj2.name) // didi
console.log(newObj2.color) // red
console.log(newObj2.isWindow()) // false

생성자 함수 안에 다른 함수 있을때

function Family(firstName) {
  this.firstName = firstName
  const names = ['bill', 'mark', 'steve']
  names.map(function(lastName, index) {
    console.log(lastName + ' ' + this.firstName)
    console.log(this)
  })
}
const kims = new Family('kim')
// bill undefined
// window
// mark undefined
// window
// steve undefined
// window

해결법

  1. bind 함수를 이용해서 해결한다.
function Family(firstName) {
  this.firstName = firstName
  const names = ['bill', 'mark', 'steve']
  const that = this
  names.map(function(value, index) {
    console.log(value + ' ' + that.firstName)
  }.bind(this))
}
const kims = new Family('kim')
  1. arrow 함수 wrapping
function Family(firstName) {
  this.firstName = firstName
  const names = ['bill', 'mark', 'steve']

  names.map((value, index) => {
    console.log(value + ' ' + this.firstName)
  })
}
const kims = new Family('kim')

결론

reference