为什么4不是Number的实例?

编程入门 行业动态 更新时间:2024-10-27 22:21:51
本文介绍了为什么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 运算符,他们尝试将参数转换('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的实例?

本文发布于:2023-08-04 23:04:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1300377.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   Number

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!