[javascript] 객체가 다른 객체를 상속받았는지 확인하는 방법
자바스크립트에서는 prototype을 이용하여 객체 간의 상속을 구현합니다. 어떤 객체가 다른 객체를 상속받았는지 확인하려면 instanceof
키워드를 사용합니다.
다음은 instanceof
를 사용하여 객체의 상속 여부를 확인하는 예시입니다.
// 부모 객체
function Animal(name) {
this.name = name;
}
// 자식 객체
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
var myDog = new Dog('Buddy', 'Golden Retriever');
console.log(myDog instanceof Dog); // true
console.log(myDog instanceof Animal); // true
위 예시에서 instanceof
를 사용하여 myDog
객체가 Dog
와 Animal
객체를 상속받았는지 확인하고 있습니다.
instanceof
는 객체가 특정 클래스의 인스턴스인지 판단할 때 유용하게 활용됩니다. 이를 통해 객체 간의 계층 구조를 파악할 수 있습니다.
더 자세한 내용은 MDN 웹 문서 instanceof를 참고하시기 바랍니다.