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. 点字符“” 在MVC Web API 2中进行请求,例如api / people / STAFF.452872. javascript - thymeleaf模板 只有length如何循环生成标签?3. javascript - node如何关闭主进程后 打开另一进程?4. 求大神指点js修改margintop导致无限下滑的问题5. node.js - 我是一个做前端的,求教如何学习vue,node等js引擎?6. golang - 用IDE看docker源码时的小问题7. docker - 各位电脑上有多少个容器啊?容器一多,自己都搞混了,咋办呢?8. java - 在Spring初始化过程中阻塞合理吗?9. web服务器 - ubuntu下布置apache加wsgi加python10. python2.7为什么点击了"开始"按钮后,tkinter上的按钮,图中红色部分,再也点不动了?

网公网安备