const Person = (function () {
// 생성자 함수
function Person(name) {
this.name = name;
}
// 프로토타입 메서드
Person.prototype.sayHello= function () {
console.log(`Hi! My name is ${this.name}`);
}
// 생성자 함수를 반환
return Person;
}());
const me = new Person('Lee');
// 인스턴스 메서드
me.sayHello = function () {
console.log(`Hey! My name is ${this.name}`);
};
// 인스턴스 메서드 호출, 인스턴스 메서드가 프로토타입 메서드를 가림
me.sayHello(); // Hey! My name is Lee
delete me.sayHello; // 인스턴스 메서드 삭제
me.sayHello(); // Hi! My name is Lee ; 프로토타입 메서드 호출
// 프로토타입 메서드 변경
Person.prototype.sayHello = function () {
console.log(`Hey! My name is ${this.name}`);
};
me.sayHello(); // Hey! My name is Lee
// 프로토타입 메서드 삭제
delete Person.prototype.sayHello;
me.sayHello(); // TypeError, 삭제됨
프로토타입은 생성자 함수 또는 인스턴스에 의해 다른 객체로 변경할 수 있다.
== 객체 간의 상속 관계를 동적으로 변경할 수 있다.
이항 연산자로서 좌변에 객체를 가리키는 식별자, 우변에 생성자 함수를 가리키는 식별자를 피연산자로 받는다.
객체 instanceof 생성자 함수
// 생성자 함수
function Person(name) {
this.name = name;
}
const me = new Person('Lee');
console.log(me instanceof Person); // true, Person.prototpye이 me 객체의 프로토타입 체인 상에 존재
console.log(me instanceof Object); // true, Object.prototpye이 me 객체의 프로토타입 체인 상에 존재
--------------------------
// 프로토타입으로 교체할 객체
const parent = {};
// 프로토타입 교체
Object.setPrototypeOf(me, parent);
// Person 생성자 함수와 parent 객체는 연결되어 있지 않다.
Person.prototype === parent // false
parent.constructor === Person // false
console.log(me instanceof Person); // false
console.log(me instanceof Object); // false
--------------------------
// parent 객체를 Person 생성자 함수의 prototype 프로퍼티에 바인딩한다.
Person.prototype = parent;
console.log(me instanceof Person); // true
console.log(me instanceof Object); // true
: 명시적으로 프로토타입을 지정하여 새로운 객체를 생성한다.
Object.create(생성할 객체의 프로토타입으로 지정할 객체, 생성할 객체의 프로퍼티 키와 프로퍼티 디스크립터 객체로 이뤄진 객체)
: 생성자 함수로 인스턴스를 생성하지 않아도 참조/ 호출할 수 있는 프로퍼티/ 메서드
: 객체 내에 특정 프로퍼티가 존재하는지 여부를 확인한다.
key : 프로퍼티 키를 나타내는 문자열
object: 객체로 평가되는 표현식
=> key in object
: 인수로 전달받은 프로퍼티 키가 객체 고유의 프로퍼티 키인 경우에만 true를 반환하고 상속받은 프로토타입의 프로퍼티 키인 경우 false를 반환한다.
for ( 변수선언문 in 객체) { ... }
: 상속받은 프로퍼티를 제외한 객체 자신의 고유 프로퍼티만 열거하는 메서드
잘 봤습니다. 좋은 글 감사합니다.