• js中的this基础


    this在js中的地位可以说是相当高了,本文介绍下this的基本相关情况,以后还会慢慢介绍

    在页面中aler(this)//this的指向是window

    在DOM操作中this的指向是当前发生事件的对象

    window.onload=function(){
            var aLi=document.getElementsByTagName('li');
    
            for(var i=0;i<aLi.length;i++){
                aLi[i].onmouseover=function(){
                    var oDiv=this.getElementsByTagName('div')[0];
                    oDiv.style.display='block';
                };
                aLi[i].onmouseout=function(){
                    var oDiv=this.getElementsByTagName('div')[0];
                    oDiv.style.display='none';
                }
            }

    但是当内部函数放到外部用一个函数名包起来的时候this的指向变了

    window.onload=function(){
            var aLi=document.getElementsByTagName('li');
            var _this=null;
            for(var i=0;i<aLi.length;i++){        
                aLi[i].onmouseover=function(){
                    _this=this;
                    //alert(this);//li
                    show();
                };
                aLi[i].onmouseout=function(){
                    _this=this;
                    hide();
                }
            }
    
            function show(){
                //alert(this);//window 如果不把this存起来 在函数里this是指向window的
                var oDiv=_this.getElementsByTagName('div')[0];
                    oDiv.style.display='block';
            }
    
            function hide(){
                var oDiv=_this.getElementsByTagName('div')[0];
                    oDiv.style.display='none';
            }
        };

    总结:

    this ——跟定义没关系、跟调用有关
    想知道this是谁——看调用的地方

    附:

    this    优先级

    高   new   系统替你创建的object
       定时器   window
       事件   发生事件的对象
       方法   对象
    低    其他   window

  • 相关阅读:
    H3CNE学习2,3 TCP-IP模型
    H3CNE学习1 课程简介
    TCPDUMP抓包学习
    Kubernetes 学习26 基于kubernetes的Paas概述
    Kubernetes 学习25 创建自定义chart及部署efk日志系统
    Linux https认证原理
    Kubernetes 学习24 helm入门
    【MySQL基础总结】索引的使用
    【MySQL基础总结】常用函数库
    【MySQL基础总结】运算符的使用
  • 原文地址:https://www.cnblogs.com/leejersey/p/3630388.html
Copyright © 2020-2023  润新知