javascript - fn.call(undefined)有什么意义
PHP中文网
PHP中文网 2017-04-10 17:21:55
[JavaScript讨论组]

在zepto.js中看到这样的代码:

 if (Array.prototype.reduce === undefined)
        Array.prototype.reduce = function(fun){
        //...省略好多代码
              accumulator = fun.call(undefined, accumulator, t[k], k, t);
        //...省略好多代码
        }

这里的参数'fun'调用使用了call的形式,有必要吗?有什么意义?
functionA.call(undefined) 和 functionA() 在我看来是没有什么区别的,他们内部的this都是指向windows对象.

补充测试:

    <script>
    var myMethod = {
        reduce1: function(fn) {
            fn.call(undefined);
        },
        reduce2: function(fn) {
            fn();
        }
    }
    var obj = {
        sum: function() {
            console.log('this in obj:', this);
        }
    }

    var sum = function() {
        console.log('this in global function:', this);
    };
    myMethod.reduce1(obj.sum);
    myMethod.reduce2(obj.sum);
    //this in obj: Window {external: Object, chrome: Object, document: document, myMethod: Object, arr: Array[5]…}
    </script>
PHP中文网
PHP中文网

认证高级PHP讲师

全部回复(3)
黄舟

为了传参数为了传参数

PHP中文网

给你传入的fun函数传递参数。

PHP中文网

函数的几种调用方法

fun.apply()
fun.call()
obj.func()
func
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号