javascript - es6数值解构Number.prototype.toString is not generic
扔个三星炸死你
扔个三星炸死你 2017-06-28 09:29:13
0
3
895
<!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不能作为函数调用?

扔个三星炸死你
扔个三星炸死你

全部回复(3)
滿天的星座

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'))
过去多啦不再A梦

你可以b.call(num),一般来说toString不允许作为普通函数执行很容易接受,就跟构造函数一般不作为普通函数执行一样。
ps:例子中的Number.prototype.toString()实际上作用域也是Number.prototype


补充一下,答题有点离题了,b()实际上是作为函数调用的,也调用成功了,错误是toString()自身抛出来的。

迷茫

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板