본문 바로가기

웹개발/javascript

자바스크립트 Object 오브젝트

 

 

자바스크립트의 ES5기반으로 한 기본 개념들입니다.  

공부했던 내용을 정리하는 용도로 오류가 있을 수 있습니다.

재배포 수정하지 마세요. 

 

 

 

 

 


 

 

Object 오브젝트 

new Object( )

var obj = new Object(111);
console.log(obj);                                           //number {111}
console.log(obj + 100);                                     //object

var obj1 = new Object();
console.log(obj1);                                           // {}

 

인스턴스를 생성하여 반환한다. 여기서 인스턴스는 파라미터의 타입에 따라 인스턴스의 타입을 정한다. 파라미터 값이 undefined이거나 null이면 빈 오브젝트 인스턴스를 반환한다. 

 

 

 

 

 

Object( )

var obj2 = Object({name: "value"});
console.log(obj2);                                          //{name: "value"}

var obj3 = {};
var obj4 = Object();

 

Object 인스턴스를 생성한다. 파라미터는 {name: value} 형태이다. 오브젝트 함수를 쓰지 않고 그냥 변수에 { }를 할당하여 Object인스턴스를 생성할 수 있다. 

 

 

 

 

 

valueOf( )

var obj = {name: "value"};
console.log(obj.valueOf());                                 //{name: "value"}

 

인스턴스의 프리미티브 값을 반환한다.

 

 

 

 

 

hasOwnProperty( ), propertyIsEnumerable( )

var b = {fruit : "apple"};
console.log(b.hasOwnProperty("fruit"));                     //true
console.log(b.hasOwnProperty("melon"));                     //false
console.log(b.hasOwnProperty("hasOwnProperty"));            //false

console.log(b.propertyIsEnumerable("fruit"));               //true

 

hasOwnProperty() : 오브젝트가 파라미터에 입력한 프로퍼티를 가지고 있는지를 평가해서 true와 false로 반환해준다. 자신이 만든 프로퍼티가 아닌 상속받은 프로퍼티라면 false를 반환한다. 

propertyIsEnumerable() : 오브젝트에서 프로퍼티를 열거할 수 있는지 없는지를 평가해서 true와 false로 반환해준다. 

 

 

 

 

 

isPrototypeOf( )

var c = new Object(123);
console.log(Object.prototype.isPrototypeOf(c));             //true

 

파라미터에 작성한 오브젝트에  오브젝트 프로토타입의 존재 여부를 평가하여 true와 false로 반환한다. 

 

 

 

 

 

toString( ), toLocaleString( )

var b = {fruit : "apple"};
var c = new Object(123);
console.log(b.toString());                                  //[object Object]
console.log(Object.prototype.toString.call(c));             //[object Number]

console.log(12345.67.toLocaleString());                     //12,345.67
console.log("12345.67".toLocaleString());                   //12345.67

 

toString() : 인스턴스 타입을 문자타입으로 반환한다.

toLocaleString( ) : 인스턴스 타입을 문자열로 반환한다. 지역화 문자 변환 메서드를 Array, Number, Date 오브젝트의 메서드에서 호출하여 사용한다. 

 

 

 

 

 


ES5에서 추가된 함수들 

defineProperty( )

var obj = {};
Object.defineProperty(obj, "apple", {value: "red", enumerable: true});
console.log(obj);                               //{apple:"red"}

 

Object.defineProperty(obj, prop, descriptor)

  • obj : 속성을 정의 할 객체.
  • prop : 새로 정의하거나 수정하려는 속성의 이름.
  • descriptor : 새로 정의하거나 속성을 기술하려는 객체.
  • 대상 오브젝트에 직접 새로운 속성을 추가하거나 이미 존재하는 속성을 수정한 후 그 객체를 반환한다. 인스턴스가 아니기 때문에 생성자에서 바로 호출을 해야한다. 

 

 

 

 

defineProperties( )

var obj = {};
Object.defineProperties(obj, 
    {apple:{value:"red",enumerable: true}, melon: {value: "green", enumerable: true}});
console.log(obj);                               //{apple: "red", melon: "green"}
for (name in obj) {
    console.log(name+":"+obj[name]);
}                                               //apple:red //melon:green

 

Object.defineProperties(obj, props)

대상 오브젝트에 여러개의 프로퍼티를 추가하거나 속성을 변경한다. 함수의 기능은 defineProperty()와 같다.

 

 

 

 

 

getPrototypeOf( ) 

function Read(point) {
    this.point = point;
  };
Read.prototype.getPoint = function(){};
Read.prototype.setPoint = function(){};
var obj = new Read(100);
var result = Object.getPrototypeOf(obj);
for(var key in result){
    console.log(key+":"+result[key])
};                                      //getPoint = function(){} //setPoint = function(){}

 

자신의 프로토 타입의 프로퍼티를 반환한다.  

 

 

 

 

 

getOwnPropertyNames( )

var obj = {};
Object.defineProperties(obj, 
    {apple:{value:"red"}, melon: {value: "green"}});
var result = Object.getOwnPropertyNames(obj);
for (var i = 0; i < result.length; i++) {
    console.log(result[i]);
}                                               //apple //melon

 

오브젝트의 프로퍼티 이름을 배열로 반환한다. 여기서 열거 가능 여부는 체크하지 않으며 자신이 만든 프로퍼티만을 대상으로 한다.

 

 

 

 

 

 

keys( )

var obj = {};
Object.defineProperties(obj, 
    {apple:{value:"red",enumerable: true}, melon: {value: "green", enumerable: false}});
var result = Object.keys(obj);
for (var i = 0; i < result.length; i++) {
    console.log(result[i]);
}                                               //apple

 

오브젝트의 프로퍼티중 열거 가능한 속성을 지닌 프로퍼티만을 배열로 반환한다. 

 

 

 

 

 


프로퍼티 디스크립터 property descriptor

 

value 속성

var obj = {};
Object.defineProperty(obj, "apple", {value: "red"});
console.log(obj);                                  //{apple:"red"}

이 속성에 설정할 값, 숫자, 문자열, 함수, 객체 등을 설정할 수 있다. 기본값은 undefined이다.  get/set 속성과 함께 사용하지 못한다.

 

 

 

 

writable

var obj = {};
Object.defineProperty(obj, "apple", {value: "red", writable: true});
obj.apple = "green";
console.log(obj);                                   //{apple:"green"}

var obj = {};
Object.defineProperty(obj, "apple", {value: "red", writable: false});
obj.apple = "green";
console.log(obj);                                   //{apple:"red"}

기본값은 false이다. true일 경우 이 속성에 설정된 값(value 값)을 할당 연산자로 수정할 수 있다. false 일 경우 값을 수정해도 에러가 나지는 않지만 바뀌지는 않는다.  get/set 속성과 함께 사용하지 못한다.

 

 

 

 

 

enumerable

var obj = {};
Object.defineProperty(obj, "apple", {value: "red", enumerable: true});
for(name in obj) {
    console.log(name+":"+obj[name]);
}                                                    //apple:red 

var obj = {};
Object.defineProperty(obj, "apple", {value: "red", enumerable: false});
for(name in obj) {
    console.log(name+":"+obj[name]);
}                                                    //

기본값은 false이다. true일 경우 해당 객체의 속성을 열거할 수 있다. false 일 경우 속성을 열거하면 에러가 나지는 않지만 값을 반환하지 않는다. 

 

 

 

 

 

 

configurable

var obj = {};
Object.defineProperty(obj, "apple", {value: "red", configurable: true});
delete obj.apple;
console.log(obj.apple);                             //undefined

var obj = {};
Object.defineProperty(obj, "apple", {value: "red", configurable: false});
delete obj.apple;
console.log(obj.apple);                             //red

기본값은 false이다. true일 경우 이 속성의 프로퍼티의 형태를 변경하거나 속성을 삭제할 수 있다. false 일 경우 프로퍼티를 삭제하거나 변경해도 에러가 나지는 않지만 바뀌지는 않는다.  

 

 

 

 

 

get

var obj = {};
Object.defineProperty(obj, "apple",{
    get: function() {
        return "red";
    }
});
var result = obj.apple;
console.log(result);                            //red

기본값은 undefined로 함수의 반환 값이 속성이 된다. obj.apple.get()으로 함수를 호출하면 에러가 난다. value/ writable과 함께 쓸 수 없다.

 

 

 

 

 

set

var obj ={}, data = {};
Object.defineProperty(obj, "apple",{
    set: function (param) {
        data.title = param;
    },
    get: function () {
        return data.title;
    }    
    });
obj.apple = "red";
console.log(obj.apple);                     //red

기본값은 undefined로 get함수에서 반환된 값을 파라미터로 이용해 값을 반환한다. value/ writable 과 함께 쓸 수 없다.

 

 

 

 

 

프로퍼티 디스크립터 함수 property descriptor function

 

getOwnPropertyDescriptor( )

var obj = {};
Object.defineProperty(obj, "apple", {value: "red", writable:true, enumerable:true});
var result = Object.getOwnPropertyDescriptor(obj, "apple");
for(var property in result) {
    console.log(property);    
}                                               //value //writable //enumerable //configurable

 

외부의 속성이 아닌 프로퍼티의 속성 이름, 값을 반환한다. 

 

 

 

 

 

preventExtensions( ),  isExtensible( )

var obj = {};
Object.preventExtensions(obj);
try{
Object.defineProperty(obj, "apple", {value: "red"}); 
} catch {
console.log("Error");
}                                               //Error
console.log(Object.isExtensible(obj));          //false

 

  • preventExtensions() : 오브젝트에 새로운 프로퍼티를 추가를 금지시킨다. 변경이나 삭제는 가능하다. 
  • isExtensible() : 오브젝트가 프로퍼티을 추가하는 것이 가능한 상태인지 확인한다. 가능하다면 true, 불가하다면 false를 반환한다.

 

 

 

 

seal( ), isSealed( )

var obj = {};
Object.defineProperty(obj, "apple", {value: "red"}); 
Object.seal(obj);
try{
    Object.defineProperty(obj, "melon", {value:"green"}); 
    delete obj.apple;
} catch {
console.log("Error");
}                                               //Error
console.log(Object.isSealed(obj));              //true

 

  • seal() : 오브젝트에 새 프로퍼티를 추가하거나 삭제하는것을 금지시킨다. 변경은 가능하다. 추가 금지는 오브젝트 단위로 삭제 금지는 프로퍼티 단위로 설정한다.
  • isSealed() : 오브젝트에 새 프로퍼티를 추가하거나 삭제하는것이 금지되었는지 여부를 확인한다. 금지되었다면 true를 금지되지 않았다면 false를 반환한다. 

 

 

 

 

 

freeze( ), isFrozen( )

var obj = {};
Object.defineProperty(obj, "apple", {value: "red"}); 
Object.freeze(obj);
try{
    Object.defineProperty(obj, "melon", {value:"green"}); 
    delete obj.apple;
    obj.apple = "pink";
} catch {
console.log("Error");
}                                               //Error
console.log(Object.isFrozen(obj));              //true

 

  • freeze() : 오브젝트에 새 프로퍼티를 추가하거나 삭제하거나 변경하는것을 모두 금지시킨다. 
  • isFrozen() : 오브젝트에 새 프로퍼티 추가, 변경, 삭제가 모두 금지 되었는지 여부를 확인한다. 만약 금지되었다면 true를 금지되지 않았다면 false를 반환한다.