为什么在JavaScript中,"3 instanceof Number" == false,但是"3..method()"会调用Number.prototype.method吗? [英] Why, in JavaScript, does '3 instanceof Number' == false, but '3..method()' will call Number.prototype.method?

查看:127
本文介绍了为什么在JavaScript中,"3 instanceof Number" == false,但是"3..method()"会调用Number.prototype.method吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于文字数严格来说不是Number的实例,为什么我可以在相应的文字对象上调用Number(或String或Boolean)对象的原型方法?这是跨浏览器的标准行为吗?

Given that a literal number not strictly an instance of Number, why can I call prototype methods of Number (or String, or Boolean) objects on the corresponding literal objects? Is this standard behavior across browsers?

发生这种情况时到底发生了什么?我怀疑这是在调用方法之前将文字强制转换为相应的类型,因为当我检查方法中的typeof this时,它返回的是对象"而不是数字".

What exactly is happening when this occurs? I suspect it's coercing the literal into the corresponding type before calling the method, because when I inspect typeof this in the method, it's returning 'object' rather than 'number'.

推荐答案

文字不被强制转换为实例.

The literal is not coerced into an instance.

内部发生的事情是创建一个实例,将值复制到该实例,并使用该实例执行该方法.然后实例被销毁.实际上并未使用文字来执行该方法.当像字符串对象一样使用字符串基元时,此包装"对象概念也将与字符串基元一起使用.此行为是标准行为.

3是数字文字.不是Number类型的实例. JavaScript具有原始数字类型和本机Number对象.

3 is a number literal. Not an instance of the Number type. JavaScript has a primitive number type and a native Number object.

来自 MDN :在要在上调用方法的上下文中 原始字符串或发生属性查找时,JavaScript会 自动包装字符串基元并调用方法或执行 属性查询.

From MDN: In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

这篇关于为什么在JavaScript中,"3 instanceof Number" == false,但是"3..method()"会调用Number.prototype.method吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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