2013-07-14 23 views
1

後我有一個叫玩家訪問屬性的jQuery的keydown

function Player(_x, _y, _speed) { 
    this.x = _x; 

    this.getX = function() { 
     return this.x; 
    }; 

    this.handleKeyDown = function(event) { 
     console.log(this.x); // undefined 
    }; 

    $(document.body).keydown(this.handleKeyDown); 
} 

爲什麼不「handleKeyDown」看不到我的x屬性的對象?我該如何解決它?

回答

0

因爲this不像你認爲它在javascript中那樣工作。 this是當前函數正在執行的上下文。所以,當你做某事像...... object.doThing(),然後執行doThing()這是指向對象。然而,你可以調用沒有對象引用的doThing(),那麼this是全局對象。

以下是您爲改用閉包概念避免this schenanigans而給出的代碼。這段代碼可以進一步重構爲使用原型,避免了一遍又一遍創建所有相同函數的額外內存開銷,但我不想用比需要的更多信息來解決這個問題。

function Player(_x, _y, _speed) { 
    var x = _x; 

    var getX = function() { 
     return x; 
    }; 

    var handleKeyDown = function(event) { 
     console.log(x); 
    }; 

    $(document.body).keydown(handleKeyDown); 
} 

在JavaScript中大開眼界的方法表明,this不工作,你最初以爲會是MDN docs for Function.prototype.apply的方式。

+0

當然,除了詞彙範圍的變量和原型不混合... – Alnitak

+0

在這種情況下,你使用'this'。 – MushinNoShin

+0

你說過_「這段代碼可以進一步重構爲使用原型」_,指代具有詞彙範圍變量的代碼。你的建議是矛盾的。 – Alnitak

0

因爲您的keydown處理程序中的this是元素本身(在本例中爲document.body)。你需要或者

var self = this; 
$(document.body).keydown(function() { self.handleKeyDown() }); 

還是看使用bind$.proxy

-1

因爲this代表了getX功能,試試這個:

function Player(_x, _y, _speed) { 
    var self = this; 
    self.x = _x; 

    self.getX = function() { 
     return self.x; 
    }; 

    self.handleKeyDown = function(event) { 
     console.log(self.x); 
    }; 

    $(document.body).keydown(self.handleKeyDown); 
} 

編輯:咩,我看了快,我的意思handleKeyDown。無論如何,this的上下文發生了變化,所以最好將它存儲在self字段中,以澄清您的代碼並確保您引用了您的想法。

0

如果使用ES5,您可以使用.bind(或舊版瀏覽器上,墊片,或使用$.proxy),以確保this設置正確:

this.handleKeyDown = function(event) { 
    console.log(this.x); 
}.bind(this); 

,或者你可以保持在一個外部參考this你的詞法範圍:

var self = this; 
this.handleKeyDown = function(event) { 
    console.log(self.x); 
}; 
0

this是 'document.body的' 在這裏,不是對象Player