instanceof 원리와 간단한 실현

4857 단어 정리
1.무엇
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
    //....
    //....
    

    좋은 웹페이지 즐겨찾기