자바 스크립트 (JavaScript)/Object Oriented JavaScript - ES5&ES2015
Using Object.create()
종우공간
2021. 8. 8. 04:09
- this is the alternative way to create object with Object.create() method
- Object.create() takes the first parameter of prototype
예제
const personPrototypes = {
greeeting: function() {
return `Hello there ${this.firstName} ${this.lastName}`;
},
getsMarried: function(newLastName) {
this.lastName = newLastName;
}
}
const mary = Object.create(personPrototypes);
// adding properties
mary.firstName = 'Mary';
mary.lastName = 'Williams';
mary.age = '30';
mary.getsMarried('Thompson');
console.log(mary.greeeting());
// different syntax
const brad = Object.create(personPrototypes, {
firstName: {value: 'Brad'},
lastName: {value: 'Traversy'},
age: {value: 36}
});
console.log(brad.greeeting());
- 첫 번째 방법에서는 프로토타입만 퍼레미터로 받아서 객체를 만들고 속성을 나중에 추가해주는 방식이다.
- 두 번쨰 방법에서는 프로토타입과 속성들을 각각 객체 형태로 받아서 객체를 만드는 방식이다.