[Javascript] 객체지향 : Object

SJ·2022년 7월 11일
0

Javascript

목록 보기
11/13

Object

Object는 객체의 가장 기본적인 형태를 가지고 있는 객체로, 모든 객체는 Object를 부모로 한다.(Object를 상속받는다.) 즉, 모든 객체는 Object의 prototype을 상속받는다.
따라서 모든 객체들에 공통으로 기능을 추가하고 싶다면 Object의 prototype 프로퍼티에 해당 기능을 추가하면 된다.

Object API 사용법

: MDN - Javascript - Object 검색

* Object.method()와 Object.prototype.method()의 차이점

// Object.keys();
const arr = ["a","b","c"];
console.log('Object.keys(arr)', Object.keys(arr));

// Object.prototype.toString()
const o = new Object();
console.log('o.toString()', o.toString());

const a = new Array(1,2,3);
console.log('a.toString()', a.toString());

Object와 메서드 사이에 prototype이 없는 경우,
Object.keys(argument) 이렇게 앞에 Object라는 객체(==생성자 함수)를 메서드와 함께 써준다.
그러나 Object와 메서드 사이에 prototype이 있는 경우,
모든 객체는 Object의 prototype을 상속받으므로 모든 객체는 toString() 메서드를 상속받는다. 따라서 위처럼 생성자 함수 new Object(), new Array()를 통해 만든 객체에 대한 메서드로 사용가능하다.

Object의 확장

Object.prototype.contain = function(neddle) {
    for(var name in this){
        if(this[name] === neddle){
            return true;
        }
    }
    return false;
}
var o = {'name':'egoing', 'city':'seoul'}
console.log(o.contain('egoing'));
var a = ['egoing','leezche','grapittie'];
console.log(a.contain('leezche'));

* Object 확장의 위험

Object.prototype.contain = function(neddle) {
    for(var name in this){
        if(this[name] === neddle){
            return true;
        }
    }
    return false;
}
var o = {'name':'egoing', 'city':'seoul'}
var a = ['egoing','leezche','grapittie'];

for(var property in o){
    console.log(property);  
} // name, city, contain

for(var i in a){
    console.log(i);  
} // 0, 1, 2, contain

객체를 for in문으로 돌려보면 확장한 프로퍼티인 contain이 포함되어 있다. Object 객체는 모든 객체에 영향을 주기 때문이다. 이것은 코드를 쓴 이의 예상과 달라 혼란을 줄 수 있다.
그래서 Object 객체는 모든 객체에 영향을 주기 때문에 확장하지 않는 것이 바람직하다.

이 문제를 회피하기 위해서는 프로퍼티가 해당 객체의 소속인지를 체크해볼 수 있는 hasOwnProperty()를 사용하면 된다. hasOwnProperty는 인자로 전달된 속성의 이름이 객체의 속성인지 여부를 판단한다. 만약 prototype으로 상속 받은 객체라면 false가 된다.

for(var realProperty in o){
    if(o.hasOwnProperty(realProperty))
        console.log(realPproperty);  
}

출처 : 생활코딩 - Javascript

0개의 댓글