Write a function that checks if a given value is an instance of a given class or superclass. For this problem, an object is considered an instance of a given class if that object has access to that class's methods.
There are no constraints on the data types that can be passed to the function. For example, the value or the class could be undefined.
Example 1:
Input: func = () => checkIfInstanceOf(new Date(), Date)
Output: true
Explanation: The object returned by the Date constructor is, by definition, an instance of Date.
Example 2:
Input: func = () => { class Animal {}; class Dog extends Animal {}; return checkIfInstanceOf(new Dog(), Animal); }
Output: true
Explanation:
class Animal {};
class Dog extends Animal {};
checkIfInstanceOf(new Dog(), Animal); // true
Dog is a subclass of Animal. Therefore, a Dog object is an instance of both Dog and Animal.
Example 3:
Input: func = () => checkIfInstanceOf(Date, Date)
Output: false
Explanation: A date constructor cannot logically be an instance of itself.
Example 4:
Input: func = () => checkIfInstanceOf(5, Number)
Output: true
Explanation: 5 is a Number. Note that the "instanceof" keyword would return false. However, it is still considered an instance of Number because it accesses the Number methods. For example "toFixed()".
출처 : https://leetcode.com/problems/check-if-object-instance-of-class/description/
풀이
function checkIfInstanceOf(obj: any, classFunction: any): boolean {
if (obj == null || obj == undefined || classFunction == undefined) {
// safety checks
return false;
}
let proto = Object.getPrototypeOf(obj);
while (proto !== null) {
if (proto === classFunction.prototype) {
return true;
}
proto = Object.getPrototypeOf(proto);
}
return false;
}
checkIfInstanceOf 함수는 주어진 객체(obj)가 특정 클래스(classFunction)의 인스턴스인지 확인하는 함수
- Object.getPrototypeOf(obj)를 사용하여 객체의 프로토타입을 가져옴.
- 현재 프로토타입(proto)이 null이 아닌 동안 루프를 계속함.
- 루프 내에서 현재 프로토타입이 클래스 함수의 프로토타입(classFunction.prototype)과 일치하는지 확인.
- 일치한다면 true를 반환.
- 일치하지 않으면, 현재 프로토타입의 프로토타입을 가져와 계속 검사
Object.getPrototypeOf(obj)
자바스크립트에서 객체의 프로토타입을 가져오는 데 사용되는 메서드
자바스크립트의 프로토타입 체계
자바스크립트는 프로토타입 기반 언어.
이는 객체가 다른 객체를 상속받을 수 있고, 이 상속 관계는 프로토타입 체인(prototype chain)이라고 불리는 연쇄적인 구조로 연결된다는 것을 의미.
- 모든 객체는 자신의 프로토타입 객체를 가리키는 숨겨진 링크를 가지고 있음. 이 링크를 [[Prototype]]이라고 부름.
- 이 [[Prototype]] 링크를 통해 객체는 부모 객체(프로토타입)로부터 속성이나 메서드를 상속받음.
- 프로토타입 체인은 객체의 상속 관계를 나타내며, 상속받은 속성이나 메서드를 찾기 위해 체인을 따라가게 됨.
function Animal() {}
Animal.prototype.speak = function() {
console.log('Animal speaks');
};
function Dog() {}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
const myDog = new Dog();
console.log(Object.getPrototypeOf(myDog)); // Dog.prototype
console.log(Object.getPrototypeOf(Dog.prototype)); // Animal.prototype
console.log(Object.getPrototypeOf(Animal.prototype)); // Object.prototype
console.log(Object.getPrototypeOf(Object.prototype)); // null
class Animal {}
class Dog extends Animal {}
const myDog = new Dog();
console.log(checkIfInstanceOf(myDog, Dog)); // true
console.log(checkIfInstanceOf(myDog, Animal)); // true
console.log(checkIfInstanceOf(myDog, Object)); // true
console.log(checkIfInstanceOf(myDog, Array)); // false
'LeetCode' 카테고리의 다른 글
| 3211. Generate Binary Strings Without Adjacent Zeros / TypeScript (0) | 2024.07.23 |
|---|---|
| 539. Minimum Time Difference / TypeScript (0) | 2024.07.21 |
| 581. Shortest Unsorted Continuous Subarray / TypeScript (1) | 2024.07.19 |
| 1156. Swap For Longest Repeated Character Substring / TypeScript (1) | 2024.07.19 |
| 1249. Minimum Remove to Make Valid Parentheses / TypeScript (1) | 2024.07.18 |