[英]Why is not a keyword for accessing “this” object outside anonymous function in JavaScript?
[英]jQuery + Javascript - accessing object fields in anonymous function
我沒有進入JavaScript OOP,所以我創建了一個包含一些要調用的函數的字段的對象。
var test = {
questions: [],
addQuestion: function(questionTitle, possibleAnwsers)
{
// not really important
},
appendQuestionToHTML: function(question)
{
// not really important
},
makeQuestionFieldsEditable: function($questionNode)
{
$questionNode.find(".questionTitle").first(function(){this.changeTextOnClick($(this));});
$questionNode.find(".questionChoice").each(function(){this.changeTextOnClick($(this));});
},
changeTextOnClick: function($spanElement)
{
// not really important
}
};
makeQuestionFieldsEditable()函數中的以下對象查找“.questionTitle”-class節點,並且所有“.questionChoice”類節點都為它們調用另一個函數。 問題是在匿名函數中使用它引用自身,而不是在字段changeTextOnClick上保存的函數。 Javascript / JQuery想要在HTMLDivElement上調用此函數,該函數不存在。
有什么解決方案嗎?
你可以使用對this
變量的引用來做到this
:
makeQuestionFieldsEditable: function($questionNode)
{
var that = this;
$questionNode.find(".questionTitle").first(function(){that.changeTextOnClick($(this));});
$questionNode.find(".questionChoice").each(function(){that.changeTextOnClick($(this));});
},
我認為您需要做的就是將'this'更改為'test'(您為此對象指定的變量)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.