美文网首页
js中call,apply,bind对比

js中call,apply,bind对比

作者: Odeng | 来源:发表于2019-07-21 17:05 被阅读0次

1.apply

apply参数列表为:1.绑定对象,2.数组参数
例如:

Math.max.apply(null, [10, 46 , 22 , -11 ])

2.call

call参数列表为:1.绑定对象,2.单独传入参数
例如:

Math.max.call(Math, 0, 46 , 22 , -11)

3.bind

bind返回值为函数,在需要的时候调用,函数中的this指向调用者

测试Demo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        var  numbers = [10, 46 , 22 , -11 ]; 
        //apply参数列表为:1.绑定对象,2.数组参数
        var  max1 = Math.max.apply(null, numbers);

        //call参数列表为:1.绑定对象,2.单独传入参数
        var max2 = Math.max.call(Math, 0, 46 , 22 , -11);
        console.log(max1);//
        //测试bind
        //bind返回值为函数,在需要的时候调用,函数中的this指向调用者
        var person = {
            name: 'name',
            hello: function (who) {
                console.log('who === this', who === this);
                return who.name + ' say hello';
            }
        };
        var me = {
            name: 'me'
        };
        var hello = person.hello.bind(me);
        console.log(hello(me));//输出me say hello
    </script>
</body>
</html>

相关文章

网友评论

      本文标题:js中call,apply,bind对比

      本文链接:https://www.haomeiwen.com/subject/xxcvlctx.html