JS 构造函数this指向问题

JavaScript024

JS 构造函数this指向问题,第1张

JS 函数被调用时 this 是指向 global(window)的。所以,你定时器里面的 this 和外面的 this 并不一样。解决方法:

function Ren( x ) {

    var me = this

    this.x = x

    this.move = function() {

        // ...

        var timer = setInterval( function() {

            if( me.x > ( mousePos.x - 100 ) ) {

                clearInterval( timer )

                return

            }

            me.x += 10

        }, 60 )    

    }

}

你只要记住JS里this无所不能。你的逻辑到哪他就指向哪。

this 里面是函数中用来表示调用这个函数的对象(js里万物皆对象),事件中,由哪个对象触发了事件则this就是谁。

举个例子:

window.onload=function(){

var oli = document.getElementsByTagName("li")

for (var i=0i<oli.lengthi=i+1){//i=3

oli[i].onclick = function () {

//this 当前调用函数的对象

console.log(this.innerHTML)

}

}

}

<ul>

<li>1</li>

<li>2</li>

<li>3</li>

</ul>