Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

Amarans

0331 JavaScript | Object | 본문

JavaScript

0331 JavaScript | Object |

Amarans 2020. 3. 31. 21:50

Object

Object 객체는 객체의 가장 기본적인 형태를 가지고 있는 객체이다. 다시 말해서 아무것도 상속받지 않는 순수한 객체다. 자바스크립트에서는 값을 저장하는 기본적인 단위로 Object를 사용한다. 

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

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

참고사이트 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object

 

Object

Object 생성자는 객체 래퍼(wrapper)를 생성합니다.

developer.mozilla.org

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 객체는 확장하지 않는 것이 바람직하다. 왜냐하면 모든 객체에 영향을 주기 때문이다. 

for(var name in o){
    console.log(name);  
}

결과 : name

        contain

확장한 프로퍼티인 contain이 포함되어 있다. 객체가 기본적으로 가지고 있을 것으로 예상하고 있는 객체 외에 다른 객체를 가지고 있는 것은 개발자들에게 혼란을 준다. 이 문제를 회피하기 위해서는 프로퍼티의 해당 객체의 소속인지를 체크해볼 수 있는 hasOwnProperty를 사용하면 된다. 

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

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

Comments