您现在的位置:首页 >> 前端 >> 内容

function里的this指向问题代码分析

时间:2018/6/12 15:30:31 点击:

  核心提示:有时候我会把事件函数里的this当成出发该事件的dom对象,其实不是这样的除非用call和aply去改变this指向,否则this是指向window的例如下面代码:form action=#邮编:in...

有时候我会把事件函数里的this当成出发该事件的dom对象,其实不是这样的除非用call和aply去改变this指向,否则this是指向window的

例如下面代码:

<form action="#">  
        邮编:<input type="text" name = "" onkeyup = "checkDate(this.value)">  
    </form>  
    <script>  
        function checkDate(value){  
            if(value.length > 6){  
                alert('邮编长度不能超过六位');  
                let textValue = value.slice(0, 6);  
                console.log(this);  
                this.value = textValue;  
            }  
        }  
    </script>  

结果为:

function里的this指向问题代码分析

但如果用call改变this情况就不一样了,this会指向触发该事件的dom对象

<form action="#">  
        邮编:<input type="text" name = "" onkeyup = "checkDate.call(this,this.value)">  
    </form>  
    <script>  
        function checkDate(value){  
            if(value.length > 6){  
                alert('邮编长度不能超过六位');  
                let textValue = value.slice(0, 6);  
                console.log(this);  
                this.value = textValue;  
            }  
        }  
    </script>  

function里的this指向问题代码分析

Tags:FU UN NC CT 
作者:网络 来源:dreamjay19