Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用对象获取位置(x,y)-Javascript_Javascript_Object_Position - Fatal编程技术网

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

使用对象获取位置(x,y)-Javascript,javascript,object,position,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){

此代码适用于:

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();

});

它不输出任何内容-我看不出我的错误在哪里。

设置间隔
设置超时
(或任何类似onclick的事件处理程序)中,
变量引用全局对象。在
窗口的浏览器中

在现代浏览器中,您可以执行以下操作:

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

}).绑定(这个),1000);// 问题是“this”的值在设置间隔内发生变化。解决方案是将其更改为:

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);
  }
}

正如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;
}

getElementById
不是全局函数,请使用
document.getElementById
您还需要限定
document.getElementById()
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();

});