第三章 web前端开发工程师--JavaScript进阶程序设计 3-6 javascript this的应用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wgf5845201314/article/details/90749023

                                          JavaScript this的应用

 

本节课所讲内容:

  1. JavaScript this介绍

2. JavaScript this的应用

主讲教师:Head老师

一. JavaScript this介绍

<!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>this 的应用</title>
</head>
<body>
    <input type="button" value="按钮" id="btn1">
    <script type="text/javascript">
/*
        //alert(this);   //指的是调用当前方法的对象
        //window.alert(this);  //调用对象this只代的是window
        oBtn = document.getElementById("btn1");
        oBtn.onclick=function(){
            alert(this);
        }                         //this指向 oBtn
        function as(){
            alert(this);
        }
        as();
        window.as();   //调用对象this只代的是window


        oBtn = document.getElementById("btn1");
        oBtn.onclick=function(){
            as();        //调用对象this只代的是window   等价于  windon.as()
        }
        //this指向 oBtn
        function as(){
            alert(this);  
        }
*/
        oBtn = document.getElementById("btn1");
        oBtn.onclick = as;   //this指向 input对象
        function as(){
            alert(this);
        }

        //window 使用到window对象比较少
    </script>
</body>
</html>

二.JavaScript this的应用

<!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>this 的应用</title>
</head>
<body>
    <input type="button" value="按钮1">
    <input type="button" value="按钮2">
    <input type="button" value="按钮3">
    <input type="button" value="按钮4">
    <script>
        var oBtn = document.getElementsByTagName('input');
        for(var i=0; i<oBtn.length; i++){
            oBtn[i].onclick = fn1;  //  fn1不带括号  this指向oBtn
        }
        function fn1(){
           // alert(this);   //已经验证this指向oBtn
           this.style.background = 'red';
        }
    </script>
</body>
</html>

 

 

猜你喜欢

转载自blog.csdn.net/wgf5845201314/article/details/90749023