打赏

js apply和call区别

<!DOCTYPE html>
<html lang="zh">

    <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>apply和call</title>
    </head>

    <body>
        <script type="text/javascript">
            function fn(n1, n2) {
                return this.a + n1 + n2
            }
            var a = 20;
            var o = {
                a: 40
            }
            console.log(fn(10, 10))
            //apply的第二个参数必须是数组
            console.log(fn.apply(o, [10, 10]))
            //call的参数 一个一个传递
            console.log(fn.call(o, 10, 10))
        </script>
    </body>

</html>

 模拟实现:

Function.prototype.call2 = function(context) {
    context.fn = this;
    var args = [];
    for(var i = 1, len = arguments.length; i < len; i++) {
        args.push('arguments[' + i + ']');
    }
    eval('context.fn(' + args +')');
    delete context.fn;
}

// 测试一下
var foo = {
    value: 1
};

function bar(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value);
}

bar.call2(foo, 'Cherry', 18); 

 

posted @ 2018-07-24 16:33  孟繁贵  阅读(547)  评论(0编辑  收藏  举报
TOP