instanceof 원리와 간단한 실현
4857 단어 정리
MDN에서는 instanceof에 대해 다음과 같이 설명합니다.
The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
instanceof
연산자는 구조 함수의prototype 속성이 대상 원형 체인의 어느 위치에 있는지 테스트하는 데 사용된다2. 실현
여기에는 이미 매우 명확하게 묘사되었는데 어떻게 실현할 것인가의 사고방식이 있다.
instanceof
왼쪽이 대상이어야 원형 체인을 찾을 수 있습니다instanceof
오른쪽은 함수여야 prototype
속성prototype
과 같지 않을 때 원형 체인을 따라 왼쪽코드:
const instance_of = (left, right) => {
// false
const baseType = ['number', 'string', 'boolean', 'undefined', 'symbol']
if(baseType.includes(typeof left)) return false
//
const RP = right.prototype
while(true) {
// , left.__proto__.__proto__.... null,
// null instanceof , Object,
if(left === null) {
return false
} else if(left === RP) {
return true
}
// ? left
left = left.__proto__
}
}
3. 주의해야 할 상황
다음 상태는 false 입니다.
/**
* 'abc' ,
* 'abc'.__proto__ === String.prototype
* , ( 'abc'.__proto__ ), ,
* new String('abc')
* 'abc' instanceof String
*/
'abc' instanceof String // false
// null , null __proto__
null instanceof Object // false
// String.__proto__.constructor.name === 'Function'
String instanceof String // false
Number instanceof Number // false
//....
//....
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
wift 정리 - URLSession + CombineCombine 또한 비동기를 처리하는 프레임워크이므로, 이를 사용하여 네트워크 작업을 간단하게 처리할 수 있다. 하지만 publisher을 사용한다면 클로저의 수많은 작업들을 Combine 연산자들로 대체할 수 있습...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.