[英]using objects to get position (x, y) - Javascript
此代碼有效:
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();
});
它什么都沒打印出來 - 我無法看出我的錯誤在哪里。
在setInterval
或setTimeout
(或任何事件處理程序,如onclick)中, this
變量引用全局對象。 在瀏覽器的window
。
在現代瀏覽器中,您可以執行以下操作:
setInterval((function() {
console.log("Left:" + that.id.offsetLeft + "px");
}).bind(this), 1000); // <------- bind
否則所有其他解決方案基本上與您的第一段代碼相似。
請注意,Mozilla的純js中有一個bind()
實現,可以移植到舊版瀏覽器。 在MDN上搜索它。
問題是“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);
}
}
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();
});
正如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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.