为了账号安全,请及时绑定邮箱和手机立即绑定

JS中的toString问题。

JS中的toString问题。

KokoTa 2015-12-07 00:34:02
如何理解({}).toString.apply([]);这句代码?例如:var arr = [1,2,3];            ({}).toString.apply(arr);//返回 function Array() { [native code] };这个前缀({})是什么含义?还有为什么调用apply或者call可以的到这个结果?PS:为啥我吧({})改为window得出的结果也是一样的?思绪有点混乱Ing......
查看完整描述

2 回答

已采纳
?
木子舟义

TA贡献33条经验 获得超4个赞

{} 是一个空对象。  等价于 var object = new Object();    {} = object  什么值都没给

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script>
        var arr = [1,2,3];
        var x = 123;
        var o = {
            x : 1,
            y : 'hehe',
            toString:function()
            {
                return this;
            }
        };
        console.log(o.toString.apply(x));
    </script>
</body>
</html>

console.log(o.toString.apply(x));

在o上调用toString但是指针指向的this 是 x (也就是NUMBER类型的toString) 返回NUMBER类型。

你的问题  ({}).toString.apply(arr);  在空对象上去调用toString。但是这个toString里的this 指向的是arr(也就是数组)。


查看完整回答
1 反对 回复 2015-12-07
?
李晓健

TA贡献1036条经验 获得超461个赞

这个只是为了改变数组的toString方法呀。

查看完整回答
反对 回复 2015-12-07
  • 2 回答
  • 0 关注
  • 1811 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信