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 - django里GROUP BY 如何写这样的mysql语句?2. 数据库安全 - 在公网上部署mysql数据库,安全方面需要做到哪些注意事项3. javascript - webpack build出错后如何定位文件?4. 求大神帮我看看是哪里写错了 感谢细心解答5. python2.7 - 在Eclipse开发Python,怎么去掉控制台输出的其他消息??6. html5 - ajax post请求后如何渲染到页面上7. 关于撑大的问题8. mysql - SQL问个基础例子,书上的,我怎么看都看不懂..谁帮我解释一下第2个为什么和第1个一样?9. 如何判断数据库的库和表是否存在?10. python - 如何使用jsom.dumps获得完整的json数据?
