使用对象获取位置(x,y) - Javascript

时间:2013-09-05 20:35:49

标签: javascript object position

此代码有效:

var myElement = document.getElementById("red"); 
    setInterval(function() {
        console.log("Left:" + myElement.offsetLeft + "px | Top:" + myElement.offsetTop + "px");
    }, 1000);

这会每秒打印出位置(x,y)

但如果我尝试将其更改为使用对象:

function Enemy(id){
    this.id = getElementById(id);
    this.getCoordinates = function(){
        setInterval(function() {
            console.log("Left:" + this.id.offsetLeft + "px | Top:" + this.id.offsetTop + "px");
        }, 1000);
    }
}

$(document).ready(function(){
    var enemy = new Enemy("red");
    enemy.getCoordinates();

});

它什么都没打印 - 我看不出我的错误在哪里。

4 个答案:

答案 0 :(得分:4)

setIntervalsetTimeout(或任何事件处理程序,如onclick)中,this变量引用全局对象。在浏览器中window

在现代浏览器中,您可以这样做:

setInterval((function() {
        console.log("Left:" + that.id.offsetLeft + "px");
    }).bind(this), 1000); // <------- bind

否则所有其他解决方案基本上与您的第一段代码相似。

请注意,Mozilla的纯js中有bind()的实现,可以移植到旧版浏览器。在MDN上搜索它。

答案 1 :(得分:2)

问题是“this”的值在setInterval中发生了变化。修复方法是将其更改为:

function Enemy(id){
  this.id = document.getElementById(id);

  var self = this;
  this.getCoordinates = function(){
    setInterval(function() {
        console.log("Left:" + self.id.offsetLeft + "px | Top:" + self.id.offsetTop + "px");
    }, 1000);
  }
}

答案 2 :(得分:1)

function Enemy(id){
    this.id = document.getElementById(id);
    this.getCoordinates = function(){
        var element = this.id;
        setInterval(function() {
            console.log("Left:" + element.offsetLeft + "px | Top:" + element.offsetTop + "px");
        }, 1000);
    }
}

$(document).ready(function(){
    var enemy = new Enemy("red");
    enemy.getCoordinates();

});

答案 3 :(得分:0)

正如slebetman所说,'this'变量不是你所期望的。尝试将其保存在'that'变量中,可以在不同的范围内访问。

function Enemy(id){
    var that = this; // reference to 'this' that can be used in other scopes
    that.id = document.getElementById(id);
    that.getCoordinates = function(){
        setInterval(function() {
            console.log("Left:" + that.id.offsetLeft + "px | Top:" + that.id.offsetTop + "px");
        }, 1000);
    }
    return that;
}