javascript - es6数值解构Number.prototype.toString is not generic
问题描述
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Document</title></head><body> <script>({toString:b} = 123);console.log(b === Number.prototype.toString); // trueconsole.log(Number.prototype.toString()); // 0console.log(b()); // Number.prototype.toString is not genericlet num = 456;console.log(num.b()); // num.b is not a function </script></body></html>
为什么b不能作为函数调用?
问题解答
回答1:Number.prototype.toString 标准
The toString function is not generic; it throws a TypeError exception if its this value is not a Number or a Number object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
翻译一下后面的:
如果他的this值不是数字类型或者Number对象,将会抛出一TypeError
直接调用this是window你可以这么用:
b.call(1)b.call(Number(’test’))回答2:
你可以b.call(num),一般来说toString不允许作为普通函数执行很容易接受,就跟构造函数一般不作为普通函数执行一样。ps:例子中的Number.prototype.toString()实际上作用域也是Number.prototype
补充一下,答题有点离题了,b()实际上是作为函数调用的,也调用成功了,错误是toString()自身抛出来的。
回答3:Number.prototype.toString 可以作为函数调用但 this 一定要是 Number 类型。其他类型的 toString 同理。
b.call(123)// '123'
The toString function is not generic; it throws a TypeError exception if its this value is not a Number or a Number object. Therefore, it cannot be transferred to other kinds of objects for use as a method.
15.7.4.2 Number.prototype.toString
相关文章:
1. python - 在sqlalchemy中获取刚插入的数据id?2. css3 - 这个效果用 CSS 可以实现吗?border-image3. 关docker hub上有些镜像的tag被标记““This image has vulnerabilities””4. javascript - 在vue-cli引入vux后 使用报错5. android - 京东移动端网页和其app加载的url所做的呈现不应该是完全一样的吗?6. 站点内容复制额外增加的版权申明,真的很反人类。试问产品自己在用这个站点吗?7. css - 移动端 盒子内加overflow-y:scroll后 字体会变大8. javascript - 奇怪的Symbol的问题9. vue.js - vue 打包后 nginx 服务端API请求跨域问题无法解决。10. javamail发送邮件是否跟所在的网络环境有关?

网公网安备