목차

Javascript Objects

  • description : Javascript Object Methods
  • author : 오션
  • email : shlim@repia.com
  • lastupdate : 2021-04-29


The source of this article

Javascript Object Methods

Example

// Create an object
let person = {
  firstName: "Elizabeth",
  lastName: "Ollsen",
  id: 5566,
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
};
 
// Display data from the object:
document.getElementById("demo").innerHTML = person.fullName();  // Elizabeth Ollsen
console.log(person);  // {firstName: "Elizabeth", lastName: "Ollsen", id: 5566, fullName: ƒ}


The this Keyword

함수 정의에서, this는 함수의 “소유자”를 나타냅니다.

위의 예제에서, thisfullName 함수를 “소유”하는 person 오브젝트입니다.

즉, this.firstNamethis objectfirstName 프러퍼티를 의미합니다.

this 키워드에 대한 자세한 내용은 The JavaScript this Keyword를 참조하십시오.

JavaScript Methods

JavaScript 메서드는 오브젝트에 대해 수행할 수 있는 작업입니다.

JavaScript 메서드는 함수 정의를 포함하는 프로퍼티입니다.

Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() { return this.firstName + “ ” + this.lastName;}


메서드는 오브젝트 프로퍼티로 저장된 함수입니다.(Methods are functions stored as object properties.)


Accessing Object Methods

다음의 구문을 사용하여 오브젝트 메서드에 액세스합니다.

objectName.methodName()


일반적으로 fullName()을 person 오브젝트의 메서드로, fullName을 프로퍼티로 설명합니다.

fullName 프로퍼티는 소괄호 ()로 호출될 때 (함수로) 실행됩니다.

다음 예제는 person 오브젝트의 fullName() 메서드에 액세스합니다.

Example

let person = {
  firstName: "John",
  lastName: "Smith",
  id: 0070,
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
};
 
document.getElementById("demo").innerHTML = person.fullName();


소괄호 ()없이 fullName 프로퍼티에 액세스하면, 함수 정의(function definition)를 반환합니다.

let person = {
  firstName: "John",
  lastName: "Smith",
  id: 0070,
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
};
 
document.getElementById("demo").innerHTML = person.fullName; // function () { return this.firstName + " " + this.lastName; }


Using Built-In Methods

다음 예제에서는 String 오브젝트의 toUpperCase() 메서드를 사용하여 텍스트를 대문자로 변환합니다:

let message = "Hello world!";
let x = message.toUpperCase();


위 코드를 실행 한 후 x의 값은 다음과 같습니다:

HELLO WORLD!

Adding a Method to an Object

오브젝트에 새로운 메서드를 추가하는 것은 쉽습니다.

Example

let person = {
  firstName: "John",
  lastName: "Doe",
  id: 4775
};
person.name = function () {
  return this.firstName + " " + this.lastName;
};
 
document.getElementById("demo").innerHTML =
  "My father is " + person.name();  // My father is John Doe