Obejct - Method


const jinsik = {
  name: 'jinsik',
  age: 30,
  sing: function(){
    console.log('노래 개못핵')
  }
}

jinsik.sing() // '노래 개못핵'

// "sing" -> method : 프로퍼티 상에 정의된 함수 
// 함수 안에 인수가 없을 경우, 펑션 생략 가능 [   sing: function(){ -> sing() ]

[객체와 Method의 관계]

let boy = {
  name : 'Jinsik 1',
  sayHello : function(){
  console.log(`Hello, I'm ${this.name}`)
 }
}

let girl = {
  name : 'Jinsik 2',
  sayHello : function(){
  console.log(`Hello, I'm ${this.name}`)
 }
}

boy.sayHello()

method "sayHello()" 상의 실행문 상의 "${this.name}" 상의 "this"는
method 앞에 점 앞에 있는 객체임 (boy)
그래서 boy.name을 불러오는 거고, jinsik 1이 불려져 옴.

* 화살표 함수는 일반 함수와는 달리 자신만의 this를 가지지 않음, 화살표 함수 내부에서 this를 사용하면, 그 this는 외부에서 값을 가져옴

let boy = {
  name : 'Jinsik 1',
  sayHello : () => {
  console.log(`Hello, I'm ${this.name}`)
 }
}

boy.sayHello()

//// Hellp, I'm Codepen
(this는 전역 객체로 되버림, this에 대해 선언된게 없기 때문)

[전역객체]
브라우저 환경 : window
Node js : global


let boy = {
  name : "jinsik",
  showName : function(){
   console.log(boy.name)
}
};

boy.showName() // jinsik

let ganjang = boy;
ganjang.name = "sunghwan"

ganjang.showName() // sunghwan

-----

let man = boy;
boy = null;

man.showName() // 에러

이럴땐 method의 시행문의 이름을 this로 바꾸면 됨
   console.log(boy.name) -> console.log(this.name)

method 상에서는 객체명을 직접 쓰는거보단 this로 쓰는게 나음 

[Methid this 상호참조]

let boy = {
  name : 'Jinsik',
  sayThis: function() {
    console.log(this);
  }
}

boy.sayThis() ///// boy 객체 전체 프로퍼티를 보여줌

(이걸 화살표 함수로 바꿀 경우)

let boy = {
  name : 'Jinsik',
  sayThis: () => {
    console.log(this);
  }
}

boy.sayThis()

this는 윈도우의 전역객체의 프로퍼티를 말하기 때문에 log가 커지므로 전체를 표출할 수 없음.

** 객체의 method를 작성할 땐 화살표함수를 사용하지 말 것.

복사했습니다!