zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    LeetCode 453 Minimum Moves to Equal Array Elements
    LeetCode 112 Path Sum
    LeetCode 437 Path Sum III
    LeetCode 263 Ugly Number
    Solutions and Summay for Linked List Naive and Easy Questions
    AWS–Sysops notes
    Linked List
    All About Linked List
    datatable fix error–Invalid JSON response
    [转]反编译c#的相关问题
  • 原文地址:https://www.cnblogs.com/leejersey/p/3630388.html
Copyright © 2011-2022 走看看