函数嵌套中,this指向对象会发生怎么样的变化?

我写了一个demo,其功能是鼠标移入时长方形块长度变长,然后高度变高,遇到如下问题:

在执行下面这段函数嵌套时

    oDiv[0].onmouseover = function(){
        that = this;
        changeStyle(that,'width',400,function(){
            changeStyle(that,'height',300);
        });
    }

必须使用that=this传参,否则浏览器会报如下错误

Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'.

我在最后贴出了整套代码,我想知道为什么用that=this传参能解决问题?不传参的话this两次分别指向了谁?chrome和firefox有没有什么好的调试方法能监视每一次this值的变化并显示出来?

html代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>animation</title>
    <link rel="stylesheet" href="animation.css" />
</head>
<body>
    <div class="wrap"></div>
    <script src="animation.js"></script>
</body>
</html>

css代码:

.wrap{
    width: 200px;
    height: 100px;
    margin: 10px;
    background-color: #f00;
    border: 4px solid black;
}

js代码:

window.onload = function(){
    var oDiv = document.getElementsByTagName('div');
    oDiv[0].timer = null;
    oDiv[0].onmouseover = function(){
        that = this;
        changeStyle(that,'width',400,function(){
            changeStyle(that,'height',300);
        });
    }
}
function changeStyle(obj,attr,iTarget,fn){
    clearInterval(obj.timer);
    var curValue = 0;
    obj.timer = setInterval(function(){
        curValue = parseInt(getStyle(obj,attr));
        var speed = (iTarget - curValue) / 20;
        speed = (speed > 0) ? Math.ceil(speed) : Math.floor(speed);
        if (curValue == iTarget) {
            clearInterval(obj.timer);
            if (fn) {
                fn();
            }
        }
        else{
            obj.style[attr] = curValue + speed + 'px';    
        }
    },30);
}
function getStyle(obj,attr){
    if (obj.currentStyle) {
        return obj.currentStyle[attr];
    }
    else{
        return getComputedStyle(obj,null)[attr];
    }
}
阅读 4.4k
5 个回答

通过事件调用的函数的this指向触发该事件的元素,所以oDiv[0].onmouseover事件调用函数的this指向的是oDiv[0];

changeStyle函数传入的回调函数的this指向的是window,因为 if (fn) { fn();}相当于window调用了该函数

如果想跟踪代码的执行情况可以采用断点调试,能看到各个变量在运行中的赋值情况

this代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。
随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象

我想你可以看看阮一峰的这篇:http://www.ruanyifeng.com/blo...

如果不传that,你的change函数,改变的是谁的样式,你知道吗?如果直接用this,this是指向window的,如一楼所说,断点,一断就知道

若不用that=this将this绑定到当前词法作用域,那么this指向的是全局对象window,这属于this的默认绑定。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题