본문 바로가기
Language/JavaScript

[JavaScript] 객체 - 객체 프로퍼티와 메소드

by jsh5408 2021. 10. 29.

객체 프로퍼티(property)

- 모든 객체는 Object 객체와 Object.prototype 객체의 모든 프로퍼티를 상속받음

- prototype 프로퍼티로 새로운 프로퍼티나 메소드 추가 가능

 

 

객체 메소드(method)

1. hasOwnProperty()
2. propertyIsEnumerable()
3. isPrototypeOf()
4. isExtensible()
5. toString()
6. valueOf()

 

 

1. hasOwnProperty()

- 특정 프로퍼티가 해당 객체에 존재하는지 검사

- 해당 객체에서 직접 선언된 프로퍼티만 검사

- 같은 이름의 프로퍼티라도 상속받은 프로퍼티는 false

function Dog(color, name, age, family) {
    this.color = color;
    this.name = name;
    this.age = age;
    this.family = family;
    this.breed = function() {
        return this.color + " " + this.family;
    }
}

const myDog = new Dog("검정색", "곰", 3, "불독");

myDog.hasOwnProperty("color"); // true
myDog.hasOwnProperty("breed"); // true
myDog.hasOwnProperty("class"); // 상속받은 프로퍼티이므로, false를 반환함.

 


2. propertyIsEnumerable()

- 특정 프로퍼티가 해당 객체에 존재하고 열거할 수 있는 프로퍼티인지 검사

- 즉, hasOwnProperty() 가 true 면서 열거할 수 있는 프로퍼티인지 검사

function Dog(color, name, age) {
    this.color = color;
    this.name = name;
    this.age = age;
}

const myDog = new Dog("흰색", "마루", 1);

// color 프로퍼티의 enumerable 속성을 false로 설정함.
Object.defineProperty(myDog, 'color', { enumerable : false} );

myDog.propertyIsEnumerable("color"); // false
myDog.propertyIsEnumerable("name");  // true
myDog.propertyIsEnumerable("age");   // true



3. isPrototypeOf()

- 특정 객체의 프로토타입 체인에 현재 객체가 존재하는지 검사

const day = new Date(); // Date 객체를 생성함.

// 객체 day의 프로토타입이 Date.prototype인지를 검사함.
Date.prototype.isPrototypeOf(day);          // true
Date.prototype.isPrototypeOf(new String()); // false

 

 

 

4. isExtensible()

- 객체에 새로운 프로퍼티를 추가할 수 있는지 검사

- 기본적으로 모든 객체는 추가 가능

- preventExtensions() 메소드로 추가할 수 없도록 설정 가능

const day = new Date(); // Date 객체를 생성함.
// 객체 day에 새로운 프로퍼티를 추가할 수 있는지 검사함.
Object.isExtensible(day); // true

// 해당 객체에 새로운 프로퍼티를 추가할 수 없도록 설정함.
const myDay = Object.preventExtensions(day);
Object.isExtensible(day); // false

 


5. toString()

- 호출한 객체의 값을 문자열로 반환

const arr = [10, "문자열", true]; // 배열
const bool = false;               // 불리언
function func() { return 0; }   // 함수

arr.toString();  // 10,문자열,true
bool.toString(); // false
func.toString(); // 함수의 소스 코드가 전부 문자열로 반환됨.



6. valueOf()

- 특정 객체의 원시 타입의 값 반환

- 원시 타입의 값을 갖고 있지 않다면 객체 자신 반환

- 원시 타입의 값이 기대되는 곳에 객체가 사용될 경우, 내부적으로 이 메소드를 호출하여 처리

function func(n) {
    this.number = n;
}

myFunc = new func(4);
console.log(myFunc + 5); // ① : [object Object]5

func.prototype.valueOf = function() { // valueOf() 메소드를 정의함.
    return this.number;
}
console.log(myFunc + 5); // ② : 9

- ① 객체 자신을 반환하여 문자열 결합 연산 수행

- ② 메소드 정의 후, 산술 연산 수행

 

 

getter 와 setter 메소드의 정의

- 접근자 프로퍼티

 

- getter : 특정 프로퍼티의 값을 받아오기 위한 메소드 => 아무런 인수 X

const gildong = { age: 18 };
console.log(gildong.age); // 18

Object.defineProperty(gildong, "americanAge", { get: function() { return this.age - 1; } });
console.log(gildong.americanAge); // 17

- get 키워드를 사용하여 getter 메소드 정의

- 해당 프로퍼티 참조 시, 미리 정의한 getter 메소드 자동 호출

 

- setter : 특정 프로퍼티의 값을 설정하기 위한 메소드 => 대입하고자 하는 값을 인수로 전달

const gildong = { age: 18 };
gildong.age = 20;
console.log(gildong.age); // 20

Object.defineProperty(gildong, "changeAge", { set: function(n) { this.age = this.age - n; } });
gildong.changeAge = 5;
console.log(gildong.age); // 15

- set 키워드를 사용하여 setter 메소드 정의

- 해당 프로퍼티의 값을 변경할 때마다 미리 정의한 setter 메소드 자동 호출

 

 

 

 

 

http://tcpschool.com/javascript/js_object_propertyMethod

 

코딩교육 티씨피스쿨

4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등

tcpschool.com

 

댓글