javascript - es6数值解构Number.prototype.toString is not generic

查看:180
本文介绍了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); // true
console.log(Number.prototype.toString()); // 0
console.log(b()); //  Number.prototype.toString is not generic

let num = 456;
console.log(num.b()); // num.b is not a function
    </script>
</body>
</html>

为什么b不能作为函数调用?

解决方案

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

直接调用thiswindow
你可以这么用:

b.call(1)
b.call(Number('test'))

这篇关于javascript - es6数值解构Number.prototype.toString is not generic的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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