developer tip

4가 Number의 인스턴스가 아닌 이유는 무엇입니까?

optionbox 2020. 11. 25. 07:54
반응형

4가 Number의 인스턴스가 아닌 이유는 무엇입니까?


호기심 :

  • 4 instanceof Number => false
  • new Number (4) instanceof Number => 참?

왜 이런거야? 문자열과 동일 :

  • 'some string' instanceof String 거짓을 반환
  • new String('some string') instanceof String => 참
  • String('some string') instanceof String 또한 false를 반환합니다.
  • ('some string').toString instanceof String 또한 false를 반환합니다.

객체, 배열 또는 함수 유형의 경우 instanceof 연산자가 예상대로 작동합니다. 나는 이것을 이해하는 방법을 모른다.

[ 새로운 통찰력 ]

Object.prototype.is = function() {
        var test = arguments.length ? [].slice.call(arguments) : null
           ,self = this.constructor;
        return test ? !!(test.filter(function(a){return a === self}).length)
               : (this.constructor.name ||
                  (String(self).match ( /^function\s*([^\s(]+)/im )
                    || [0,'ANONYMOUS_CONSTRUCTOR']) [1] );
}
// usage
var Newclass = function(){};  // anonymous Constructor function
var Some = function Some(){}; // named Constructor function
(5).is();                     //=> Number
'hello world'.is();           //=> String
(new Newclass()).is();        //=> ANONYMOUS_CONSTRUCTOR
(new Some()).is();            //=> Some
/[a-z]/.is();                 //=> RegExp
'5'.is(Number);               //=> false
'5'.is(String);               //=> true

value instanceof Constructor동일 Constructor.prototype.isPrototypeOf(value)하며 둘 다 [[Prototype]] 체인 value에서 특정 개체의 발생 여부를 확인합니다.

문자열과 숫자는 객체가 아니라 원시 값 이므로 [[Prototype]]이 없으므로 일반 객체 (Java에서 'boxing'이라고 함)로 래핑하는 경우에만 작동합니다.

당신은 눈치로도, String(value)그리고 new String(value)다른 일을 : 당신이 사용하지 않고 내장 유형의 생성자 함수를 호출하면 new연산자, 그들은 변환 ( '캐스트') 특정 유형의 인수하려고합니다. 당신이 사용하는 경우 new연산자를, 그들은 래퍼 개체를 만듭니다.

new String(value)는와 거의 동일 Object(String(value))하며 new Object(String(value)).


JavaScript의 유형에 대한 추가 정보 : ECMA-262는 Undefined , Null , Boolean , NumberString 과 같은 기본 유형을 정의합니다 . 또한 속성을 가진 사물에 대한 유형 Object 가 있습니다.

예를 들어, 함수는 Object 유형 ([[Call]]이라는 특수 속성 만 있음)이며 Nullnull 유형의 기본 값입니다 . 이것은 연산자 의 결과가 실제로 값의 유형을 반환하지 않음을 의미합니다 .typeof

또한 JavaScript 객체에는 [[Class]]라는 또 다른 속성이 있습니다. 를 통해 얻을 수 있습니다 Object.prototype.toString.call(value)(이 반환됩니다 ). 배열과 함수는 Object 유형 이지만 해당 클래스는 ArrayFunction 입니다.'[objectClassname]'

위에 주어진 객체 클래스에 대한 테스트는 instanceof실패 할 때 작동 합니다 (예 : 객체가 창 / 프레임 경계 사이를 통과하고 동일한 프로토 타입을 공유하지 않는 경우).


또한이 개선 된 버전을 확인하는 것이 좋습니다 typeof.

function typeOf(value) {
    var type = typeof value;

    switch(type) {
        case 'object':
        return value === null ? 'null' : Object.prototype.toString.call(value).
            match(/^\[object (.*)\]$/)[1]

        case 'function':
        return 'Function';

        default:
        return type;
    }
}

프리미티브의 경우 유형소문자로 반환하고 객체의 경우 클래스제목 케이스로 반환합니다 .

예 :

  • 의 기본 요소 유형 번호 (예를 들어 5), 그것은 반환 'number'의 래퍼 개체를, 클래스 번호 (예 new Number(5))가 반환됩니다 'Number';

  • 함수의 경우 'Function'.

기본 값과 래퍼 객체를 구분하고 싶지 않다면 (아마도 나쁜 이유가 무엇이든간에) typeOf(...).toLowerCase().

Known bugs are some built-in functions in IE, which are considered 'Object' and a return value of 'unknown' when used with some COM+ objects.


You may try to evaluate:

>>> typeof("a")
"string"
>>> typeof(new String("a"))
"object"
>>> typeof(4)
"number"
>>> typeof(new Number(4))
"object"

As stated in Christoph's answer, string and number literals are not the same as String and Number objects. If you use any of the String or Number methods on the literal, say

'a string literal'.length

The literal is temporarily converted to an object, the method is invoked and the object is discarded.
Literals have some distinct advantages over objects.

//false, two different objects with the same value
alert( new String('string') == new String('string') ); 

//true, identical literals
alert( 'string' == 'string' );

Always use literals to avoid unexpected behaviour!
You can use Number() and String() to typecast if you need to:

//true
alert( Number('5') === 5 )

//false
alert( '5' === 5 )

In the case of primitive numbers, the isNaN method could also help you.


This is a nuance of Javascript which I've found catches some out. The instanceof of operator will always result in false if the LHS is not an object type.

Note that new String('Hello World') does not result in a string type but is an object. The new operator always results in an object. I see this sort of thing:

function fnX(value)
{
     if (typeof value == 'string')
     {
          //Do stuff
     }
}
fnX(new String('Hello World'));

The expectation is that "Do Stuff" will happen but it doesn't because the typeof the value is object.

참고URL : https://stackoverflow.com/questions/472418/why-is-4-not-an-instance-of-number

반응형