반응형

Object.create함수의 구현 방법을 살펴보면 Object.create와 별도로 객체를 초기화하고 있는 것을 볼 수 있다.

이러한 과정을 하나의 함수로 묶어서 객체별로 간단한 상속 함수를 만들 수도 있지만, 표준의 Object.create함수는 2번째 인자를 선택적으로 받아서 객체를 초기화하도록 되어 있다.

 

Object.create함수로 값을 초기화하는 예

function Person(name) {
    this.name = name;
}
Person.prototype = {
    yell: function() {
        alert("my name is " + this.name);
    }
};

var shiro = Object.create(Person.prototype, {
    name: {
        value: "Shrio"
    }
});
shiro.yell(); // Shiro

shiro.name = "Jun";
shiro.yell(); // Shiro

이렇게 Object.create함수를 통해서 값만 설정하면 읽기 전용 속성이 되어 값을 수정할 수 없게 된다. 따라서 값을 수정할 수 있게 하려면 해당 속성에 대하여 추가로 설정해주어야 한다.

 

Object.create함수로 수정 가능한 속성 초기화 예

function Person(name) {
    this.name = name;
}
Person.prototype = {
    yell: function() {
        alert("my name is " + this.name);
    }
};

var shiro = Object.create(Person.prototype, {
    name: {
        value: "Shrio",
        configurable: true,
        enumerable: true,
        writable: true
    }
});
shiro.yell(); // Shiro

shiro.name = "Jun";
shiro.yell(); // Jun

 

Object.defineProperty설정 파라미터

속성 내용 기본값
value 설정할 속성의 값 undefined
configurable 속성을 지우거나 value속성 이외의 설정 속성을 바꿀지 여부 false
enumerable for-in루프에서 해당 속성도 참조할지 여부 false
writable 속성의 값을 설정 가능 여부 false
get 속성을 참조하게 되면 참조용으로 호출할 함수 undefined
set 속성을 설정하게 되면 설정용으로 호출할 함수 undefined

 

접근자 활용 예

function Person(name) {
    this.name = name;
}
Person.prototype = {
    yell: function() {
        alert("my name is " + this.name);
    }
};

var shiro = Object.create(Person.prototype, {
    name: {
        value: "Shrio",
        configurable: true,
        enumerable: true,
        writable: true
    }
});
shiro.yell(); // Shiro

shiro.name = "Jun";
shiro.yell(); // Jun

Object.defineProperties(shiro, {
    firstName: {
        value: "Ko",
        writable: true
    },
    lastName: {
        value: "Shiro",
        writable: true
    },
    fullName: {
        get: function() {
            return this.firstName + " " + this.lastName;
        },
        set: function(value) {
            var res = value.split(" ");
            if(res.length > 1) {
                this.firstName = res[0];
                this.lastName = res[1];
            } else {
                alert("Wrong format");
            }
        }
    }
});

console.log(shiro.fullName); // Ko Shiro
shiro.fullName = "Hello World";
console.log(shiro.firstName); // Hello
console.log(shiro.lastName); // World

이렇게 다른 속성들을 조합하여 하나의 새로운 속성을 만들 때와 반대로 설정을 다른 속성으로 투영하고자 할 때 get과 set속성을 사용하면 편리하게 이용할 수 있다. 이처럼 객체를 생성할 때 Object.create를 사용하면 조금 더 다양하게 변수를 특징적으로 설정할 수 있고 속성 간의 관계도 편리하게 설계할 수 있다.

반응형

+ Recent posts