是否可以覆盖javaScript原始数据类型? [英] Is it possible to overwrite javaScript primitive data type?

查看:79
本文介绍了是否可以覆盖javaScript原始数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是自我解释的。我知道可以扩展原始数据类型,例如 string 但是可以覆盖它吗?

Question is self explanatory. I know it is possible to extend primitive data types such as string but is it possible to overwrite it?

这个是一个在面试中被问过的问题。

This is a question that has been asked in an interview.

推荐答案

不,你不能覆盖任何东西。 EcmaScript 定义基元类型 未定义 Null Boolean Number 字符串;这些是内部的,无论你在做什么都会被使用(例如覆盖全局 String 构造函数)。 类型转换和文字评估不依赖于任何公共功能,只使用这些内部类型和算法为他们指定。

No, you cannot overwrite anything. EcmaScript defines the primitive types Undefined, Null, Boolean, Number, and String; these are internal and will be used regardless of what you are doing (for example overwriting the global String constructor). Type conversion and evaluation of literals does not rely on any public functions but uses only these internal types and the algorithms specified for them.

当然,如果有人用 String(myval)而不是<$ c进行字符串强制$ c>+ myval 分配给全局 String 变量将对该代码产生影响。任何内部使用仍将指向旧函数。

Of course, if someone does string coercion with String(myval) instead of ""+myval assigning to the global String variable will have an effect on that code. Any internal use would still point to the "old" function.

如果您正在讨论基元类型的原型对象(当使用作为对象时),这些也不可覆盖。您可以扩展这些对象,但只要您分配给例如 Number.prototype 您刚刚丢失了对实际原始数字protype对象的引用。 数字构造函数的示例规范:

If you were talking about prototype objects for the primitive types (when used as objects), those are not overwritable as well. You may extend those objects, but as soon as you assign to e.g. Number.prototype you just have lost a reference to the actual, original number protype object. Example spec for The Number constructor:

新构造对象的[prototype]设置为原始 Number原型对象,初始值 Number.prototype 15.7.3.1

The [prototype] of the newly constructed object is set to the original Number prototype object, the one that is the initial value of Number.prototype (15.7.3.1)

这篇关于是否可以覆盖javaScript原始数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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