• call与apply


    //哪四种情况下不能用this
    //1,行间;2,套一层;3,定时器;4,绑定

    用于设置this的值

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    
    </body>
    </html>
    <script type="text/javascript">
        function show(a,b) {
            console.log("this是"+this+",a是"+a+",b是"+b);
        }
        show(1,2);//window
        //call中的参数可以是多个,第一个是this,后面的参数往下排列
        //show.call(this,参数)
        show.call(12,1,2);//12
        //跟call的作用相似的还有apply,只不过它只有两个参数,第一个是this,第二个是一个数组
        //show.apply(this,[参数]);
        show.apply(12,[1,2]);//
    
        //call与apply区别仅仅在于参数传递的方法上。
    </script>

    使用的地方:

    function myAddEvent(obj, sEv, fn)
    {
    // 总结起来就是:
    // attachEvent——兼容:IE7、IE8;不兼容firefox、chrome、IE9、IE10、IE11、safari、opera
    // addEventListener——兼容:firefox、chrome、IE、safari、opera;不兼容IE7、IE8
        if(obj.attachEvent)
        {
            obj.attachEvent('on'+sEv, function (){
                fn.call(obj);//如果不用call,this的指向就是window,用call确保this的指向为当前的obj
            });
        }
        else
        {
            obj.addEventListener(sEv, fn, false);//给元素绑定事件,函数
        }
    }
  • 相关阅读:
    CodeForces-1263D Secret Passwords 并查集 求连通分量
    Virtual Friends HDU
    AreYouBusy HDU
    Jack Straws POJ
    Divisibility by 25 CodeForces
    逃离迷宫 HDU
    Find a way HDU
    Stall Reservations POJ
    Three displays CodeForces
    Radar Installation POJ
  • 原文地址:https://www.cnblogs.com/wang715100018066/p/6289292.html
Copyright © 2020-2023  润新知