Object

Object 객체

Object 객체는 객체의 가장 기본적인 형태를 가지고 있는 객체로, 아무것도 상속받지 않는 순수한 객체

동시에 자바스크립트의 모든 객체는 Object 객체를 상속받기 때문에 모든 객체는 Object 객체의 Property를 가짐

var grades = {'egoing': 10, 'k8805': 6, 'sorialgi': 80};

1. Object API 사용법

//Object.keys() : Key값을 리턴해주는 Method
var arr = ["a", "b", "c"];
console.log('Object.keys(arr)', Object.keys(arr)); // ["0", "1", "2"]
//인자로 arr을 받아서 처리

//Object.prototype.toString()
var a = [1,2,3];
a.toString(); //1,2,3

//Object.prototype.tostring() : tostring()은 문자열을 반환하는 object의 대표적인 방법
var o = new Object();
console.log('o.toString()', o.toString()); //o.toString() [object Object]
var a = new Array(1,2,3);
console.log('a.toString()', a.toString()); //a.toString() 1,2,3
//object의 method인 toString()을 prototype을 통해 사용가능

2. Object 확장

Object 객체를 확장하면 모든 객체가 접근할 수 있는 API를 만들 수 있음

Object.prototype.contain = function(neddle) {
    for(var name in this){ //this는 var o 또는 var a
        if(this[name] === neddle){
            return true; //찾는 인자값이 있다면 true
        }
    }
    return false; //찾는 인자값이 없다면 false 
}
var o = {'name':'egoing', 'city':'seoul'}
console.log(o.contain('egoing')); //true
var a = ['egoing','leezche','grapittie'];
console.log(a.contain('leezche')); //false

3. Object 확장의 위험

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 name in o){
    console.log(name);
} //name,city,contain → 확장 프로퍼티인 contain이 포함됨
for(var name in a){
    console.log(name);
} //0,1,2,contain → 확장 프로퍼티인 contain이 포함됨

3-1. Object 확장 위험의 회피

.hasOwnProperty() : Property의 해당 객체의 소속인지를 체크해볼 수 있음

hasOwnProperty는 인자로 전달된 속성의 이름이 객체의 속성인지 여부를 판단 만약 prototype으로 상속 받은 객체(ex. contain)라면 false

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 name in o){
    if(o.hasOwnProperty(name)){
        console.log(name);  
    }
} //name, city

for(var name in a){
    if(a.hasOwnProperty(name)){
        console.log(name);  
    }
} //0, 1, 2

Last updated