为什么4不是Number的实例? [英] Why is 4 not an instance of Number?

查看:91
本文介绍了为什么4不是Number的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好奇:




  • 4 instanceof Number => false

  • new Number(4) instanceof Number => true?



这是为什么?与字符串相同:




  • '某些字符串'instanceof String 返回false

  • new String('some string')instanceof String => true

  • 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;
返回测试? !!(test.filter(function(a){return a === self})。length)
:(this.constructor.name ||
(String(self).match(/ ^ function \s *([^ \s(] +)/ im)
|| [0,'ANONYMOUS_CONSTRUCTOR'])[1]);
}
//用法
var Newclass = function(){}; //匿名构造函数
var Some = function Some(){}; //命名构造函数
(5).is(); // => Number
'hello world'.is(); // => String
(new Newclass())。is(); // => ANONYMOUS_CONSTRUCTOR
(new Some())。is(); // =>一些
/ [az] /。是(); // => RegExp
'5'。is(Number); // => false
'5'.is(String); // => true


解决方案

value instanceof构造函数相同Constructor.prototype.isPrototypeOf(value)并检查[[Prototype]] - 链对于特定对象的出现,



字符串和数字是原始值,而不是对象,因此没有[[Prototype]],因此它只能工作如果你将它们包装在常规对象中(在Java中称为'boxing')。



另外,正如你所注意到的, String(value) new String(value)执行不同的操作:如果在不使用 new <的情况下调用内置类型的构造函数/ code>运算符,他们尝试将参数转换('cast')到特定类型。如果你使用 new 运算符,他们会创建一个包装器对象。



new String(值)大致相当于 Object(String(value)),其行为与 new Object(String)相同(值))






JavaScript中的类型更多:ECMA-262定义了以下原始类型:未定义 Null 布尔数字字符串。此外,对于具有属性的东西,还有 Object 类型。



例如,函数的类型为 Object (它们只有一个名为[[Call]]的特殊属性,而 null Null 类型的原始值。这意味着 typeof 运算符的结果并不真正返回值的类型...



另外,JavaScript对象具有另一个名为[[Class]]的属性。您可以通过 Object.prototype.toString.call(value)获取它(这将返回'[object 类名称 ]')。数组和函数的类型为 Object ,但它们的类是 Array Function



instanceof 失败时(例如,当对象在窗口/框架边界之间传递并且不共享相同的原型时),上面给出的对象类的测试有效。 / p>




此外,您可能想要查看 typeof :

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

开关(类型){
case'object':
返回值=== null? 'null':Object.prototype.toString.call(value)。
匹配(/ ^ \ [object(。*)\] $ /)[1]

case'function':
返回'Function';

默认值:
返回类型;
}
}

对于基元,它将返回类型 小写,对于对象,它会在标题大小写中返回



示例:




  • 对于类型的原语 Number (例如 5 ),对于包装器对象,它将返回'number' 数字(例如 new Number(5)),它将返回'Number ';


  • 对于函数,它将返回'Function'




如果你不想辨别原始值和包装器对象(无论是什么,可能是坏的原因),使用 typeOf(...)。toLowerCase()



已知错误是IE中的一些内置函数一些被认为是'对象',当与某些人一起使用时,返回值'unknown' COM +对象。


Just curious:

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

Why is this? Same with strings:

  • 'some string' instanceof String returns false
  • new String('some string') instanceof String => true
  • String('some string') instanceof String also returns false
  • ('some string').toString instanceof String also returns false

For object, array or function types the instanceof operator works as expected. I just don't know how to understand this.

[new insights]

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 is the same as Constructor.prototype.isPrototypeOf(value) and both check the [[Prototype]]-chain of value for occurences of a specific object.

Strings and numbers are primitive values, not objects and therefore don't have a [[Prototype]], so it'll only work if you wrap them in regular objects (called 'boxing' in Java).

Also, as you noticed, String(value) and new String(value) do different things: If you call the constructor functions of the built-in types without using the new operator, they try to convert ('cast') the argument to the specific type. If you use the new operator, they create a wrapper object.

new String(value) is roughly equivalent to Object(String(value)), which behaves the same way as new Object(String(value)).


Some more on types in JavaScript: ECMA-262 defines the following primitive types: Undefined, Null, Boolean, Number, and String. Additionally, there is the type Object for things which have properties.

For example, functions are of type Object (they just have a special property called [[Call]]), and null is a primitive value of type Null. This means that the result of the typeof operator doesn't really return the type of a value...

Aditionally, JavaScript objects have another property called [[Class]]. You can get it via Object.prototype.toString.call(value) (this will return '[objectClassname]'). Arrays and functions are of the type Object, but their classes are Array and Function.

The test for an object's class given above works when instanceof fails (e.g. when objects are passed between window/frame boundaries and don't share the same prototypes).


Also, you might want to check out this improved version of 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;
    }
}

For primitives, it will return their type in lower case, for objects, it will return their class in title case.

Examples:

  • For primitives of type Number (eg 5), it will return 'number', for wrapper objects of class Number (eg new Number(5)), it will return 'Number';

  • For functions, it will return 'Function'.

If you don't want to discern between primitive values and wrapper objects (for whatever, probably bad reason), use 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.

这篇关于为什么4不是Number的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆