
코어자바스크립트 ch6. 프로토타입를 읽고 정리한 내용입니다.
var Person = function (name) {
this._name = name;
};
Person.prototype.getName = function() {
return this._name;
};
var suzi = new Person('Suzi');
suzi.__proto__.getName(); // undefined
Person 인스턴스의 __proto__는 Person의 prototype을 상속한다고 한다.
그렇다면 suzi.__proto__.getName()은 ‘Suzi’를 출력 해야 하는거 아닌가?
그런데 왜 undefined가 뜰까?
suzi.__proto__의 객체 내부에는 name 프로퍼티가 없기 때문이라고 한다.
즉, __proto__는 Constructor의 prototype은 참조한다.
하지만 인스턴스가 생성한 name 프로퍼티는 알지 못한다. 따라서 undefined가 할당된다.
하지만, suzi.getName()은 가능하다.
suzi는 name 프로퍼티를 알고 있기 때문이다.
function Member(name) {
this.name = name;
this.sayHello = function() {
console.log(`hi, ${name}`);
}
}
const member1 = new Member('철수')
const member2 = new Member('영희')
function Member(name) {
this.name = name;
}
Member.prototype.sayHello = function () {
console.log(`hi, ${name}`);
}
const member1 = new Member('철수')
const member2 = new Member('영희')
console.log(member1.sayHello === member2.sayHello) // true
싱글톤 패턴은 인스턴스가 오직 하나만 존재하도록 보장하는 설계 패턴이다.
생성자 함수를 통해 새로운 인스턴스를 생성하더라도 기존에 생성했던 단 하나의 인스턴스만 바라본다.
let instance = null;
function Singleton(data = 'Initial data') {
if (instance) {
return instance;
}
this.data = data;
instance = this;
}
Singleton.prototype.getData = function() {
return this.data;
}
Singleton.prototype.setData = function(data) {
this.data = data;
}
즉시 실행함수 내부에 instance 변수를 선언하여 외부에서 직접 접근을 막는다.
const Singleton = (function(){
let instance;
function Constructor() {
// 생성자 로직
}
Constructor.prototype.someMethod = function() {
console.log('This is a method shared by all instances');
};
return {
getInstance: function() {
if (!instance) {
instance = new Constructor();
}
return instance;
}
};
})();
let obj1 = Singleton.getInstance();
let obj2 = Singleton.getInstance();
console.log(obj1 === obj2); // true
obj1.someMethod(); // "This is a method shared by all instances"
var Person = function (name) {
this.name = name;
};
Person.prototype.getName = function () {
return this.name;
};
var iu = new Person("지금");
iu.getName = function () {
return "바로 " + this.name;
};
console.log(iu.getName());
__proto__를 검색하는 순서로 진행된다.__proto__를 통해 부모의 프로퍼티를 검색할 수 있다.