개발기록/Javascript
[javascript] function 생성자함수
네이처리
2022. 9. 3. 09:20
728x90
반응형
공부하면서 정리한 내용입니다
참고한 내용은 맨 아래의 링크를 확인해주세요
function Person() {
this.name = "annonymous";
this.sayHello = function() {
console.log("Hello, my name is" + this.name);
}
}
function Yoda() {
let obj = new Person();
obj.name = "Yoda";
return obj;
}
let uuu = new Yoda();
uuu.sayHello(); // Hello, my name isYoda
console.log(uuu instanceof Yoda); // false
console.log(uuu instanceof Person); // true
▲ uuu의 인스턴스는 Yoda가 아닌 Person으로 나옵니다.
이러한 문제 때문에 function에서 기본적으로 제공하는 prototype을 이용한 방법이 등장 하였습니다.
let person = {
name: "annoymous",
sayHello: function() {
console.log("Hello, my name is " + this.name);
}
};
function Yoda() {
this.name = "Yoda";
}
Yoda.prototype = person;
let yoda = new Yoda();
yoda.sayHello(); // Hello, my name is Yoda
person.sayHello(); // Hello, my name is annoymous
console.log(yoda instanceof Yoda); // true
console.log(yoda instanceof person); // Right-hand side of 'instanceof' is not callable
▲ person이 함수형태가 아니기 때문에, instanceof Person를 이용한 부모객체 확인이 불가능합니다.
console.log(uuu);

instanceof
이 연산자를 사용하면 객체가 특정 클래스에 속하는지 아닌지를 확인할 수 있습니다. 상속 관계도 확인해줍니다.
console.log(변수 instanceof Class_name); // boolean
console.log([1,2,3] instanceof Array); // true
console.log([1,2,3] instanceof Object); // true
Array는 프로토타입 기반으로 Object를 상속받습니다.
Reference
자바스크립트(JavaScript) 상속과 프로토타입 개념정리
자바스크립트에는 클래스라는 개념대신 기존의 객체를 복사하여 새로운 객체를 생성하는 프로토타입 언어입니다. 프로토타입은 크게 두 가지로 나뉘어 집니다. 프로토타입 객체를 참조하는 pro
shlee1353.github.io
[JavaScript] 함수 생성자와 클래스의 차이
함수 생성자(Constructor Functions)란? 함수 생성자는 여러 프로그래밍 언어에서는 '클래스'와 동의어다. 어떤 경우 사람들은 참조 타입(Reference Types), 클래스(Classes), 데이터 타입, 아니면 간단하게 생
uiyoji-journal.tistory.com
'instanceof'로 클래스 확인하기
ko.javascript.info
728x90
반응형