JS 문법 - 메소드

KODYwiththeK·2022년 12월 2일
0

JavaScript

목록 보기
9/32

JS 문법 - 메소드

Class: 제로베이스
Created: November 30, 2022 1:40 PM
Type: Javascript
강의 명: 이론부터 실전까지 모든 것을 담은 자료구조/알고리즘

함수 선언식

변수 선언이 var로 시작해야하는 것처럼 함수 선언은 function으로 시작한다.
선언된 함수는 나중 사용을 위해 저장되며, call 될 때 실행된다..

function foo() {
	return "이것은 함수입니다.";
}

함수 표현식

함수 표현식이 변수에 저장되면, 변수는 함수처럼 사용 가능해진다. 변수에 저장된 함수는 함수명이 필요 없으며, 변수 이름을 통하여 호출된다.

var x = function (a, b) {return a * b};

함수 저장

배열의 요소 혹은 객체의 속성에 함수를 정의해서 사용 가능하다.

let list = [
  "john", 
  27, 
  function hello() {
    console.log("hello");
  },
];
list[2](); // hello

let obj= {
  name: "john",
  age: 27,
  hello() {
    console.log("hello");
  }
};
obj.hello(); // hello

function hello() { 
  return console.log("hello");
}
hello(); // hello

메소드 method

객체에 저장된 값이 함수인 경우, 이를 메서드 라고 부른다.

function hello() { 
  return console.log("hello");
}
hello(); // hello

let obj= {
  name: "john",
  age: 27,
  func: hello,
};
obj.func(); // hello

객체의 변수 메모리영역에는 참조 주소만을 가지고 있다.

객체에 저장된 함수 프로퍼티 내에도 저장된 것은 주소 값이고, 이 주소값이 저장된 함수명을 통해 실제 함수를 호출하는 것.

this

객체 안의 메서드에서 객체 내부의 속성(property)값을 접근할 수 있는 지시자

let obj= {
  name: "john",
  age: 27,
  hello_func() {
    console.log("hello" + this.name);
  },
};
obj.hello_func(); // hello john
  • hello_func 내의 this 는 obj의 주소값을 가리킨다.
  • 따라서 this.name 을 통해 obj 객체 내의 name 속성의 값에 접근하는 것.

예제 )

this를 사용하는 method는 추가 가능하며, 이 때 this는 runtime애 결정되어 호출한 객체에 따라 다름

let user = { name: "john" };
let admin = { name: "kody" };
//함수 hello_func 선언
function hello_func() {
  console.log("hello " + this.name);
}
//객체 내 속성으로 hello_func 함수 추가
user.func = hello_func
admin.func = hello_func
//객체 내 함수(메소드) 호출
user.func()  //hello john
admin.func() //hello kody
//아래와 같은 접근 방법도 있음
user["func"]  //hello john
admin["func"] //hello kody
profile
일상 속 선한 영향력을 만드는 개발자를 꿈꿉니다🧑🏻‍💻

0개의 댓글

관련 채용 정보