const me = {
name : "pudding",
talk() {
return `hello ${this.name}`;
}
};
const bf = {
name : "schatz",
talk(){
return `${this.name} sprichst deutsch`;
}
};
me.name = "jeong";
//이름 바꾸기 싫은데 바뀜.. 버그가 이런 곳에서 많이 일어난다.
document.write(me.name);
문제점
1.변수 값을 마음대로 바꿈
2.talk() 이라는 함수는 안에 이름만 바꼈지, 똑같은 기능을 하고 있는데 두번 쓰고 있음
따라서 factoryFunction을 써서 , 똑같은 프로퍼티 성질을 가지고 있는 객체를 여러개 만들 수 있음
Factory Function은 함수가 실행되고 리턴되는 순간에 새로운 객체를 생성하는데, parameter 정의를 해주지 않아도 함수는 만들 수 있다.
왜냐하면 parameter만 상속받아서 새로운 객체를 생성할 수 있기 때문이다.
1.name을 정의 안해도 만들 수 있음
function createPerson(name){
return{
getFullName():
`my ${name} is pudding`;
}
}
const pudding = createPerson("pudding");
pudding.name = "jeong";
console.log(pudding.name); // undefined로 나온다. return 객체에 정의되지 않아서 밖에서 마음대로 못바꿈
2.name을 정의해서 만드는 경우
function createPerson(name){
return{
name : name,
getFullName():
`my ${name} is pudding`;
}
}
반면에 생성자의 경우 , 함수 실행시 , 새로운 객체를 리턴하는 factory function과는 다르게 내부적으로 this 객체를 리턴해준다. 이때 this객체는 parameter 값을 전달받아야 그 복사한 인스턴스 변수가 parameter를 쓸 수 있고 마음대로 프로퍼티를 추가하거나 바꿀 수 있다.
function Person(name,age){
//this = {};
this.name = name;
this.age = age;
//return this }
const pudding = new Person("pudding",29);
factory function benefits
1.simple
2.no duplicate
3.data privacy
개발자들 대부분 factory function을 많이 쓴다고 한다.
constructor랑 비슷한데, factory function은 객체 자체를 만들어주는 것이고, 변수값 접근이 어려워 보안상 더 좋다(버그를 줄일 수 있다.)
https://dev.to/bchau/factory-functions-vs-constructors-500m
Factory Functions vs Constructors
To grasp the concept of factory functions and constructors, you must first understand functions and...
dev.to
'Development (국비 복습 ) > JavaScript' 카테고리의 다른 글
자바스크립트 .el? (0) | 2023.02.21 |
---|---|
배열 요소 삭제방법 (0) | 2023.02.21 |
생성자(constructor)와 prototype , __proto__ (0) | 2023.02.19 |
Javascript reference (0) | 2023.02.19 |
이전사진 다음사진 변경 (0) | 2023.02.19 |
댓글