在下面的javascript代碼中,我想知道哪個對象「this」指向。但是相反,我得到一個函數。「this」返回一個函數而不是對象
我認爲「this」總是指向調用該函數的對象。 那麼任何人都可以解釋爲什麼這種行爲?
$(document).ready(function() {
var Paper = function() {};
Paper.prototype = {
populate: function(data) {
data.questions.forEach(function(entry) {
//printing a function instead of object
console.log(this);
}.bind(this));
}
};
var paperDataLoader = function() {
this.callbacks = [];
};
paperDataLoader.prototype = {
//accepts a callback to notify the registered function
registerDataLoaded: function(callback) {
this.callbacks.push(callback);
},
//calls the callback functions when data is loaded
loadData: function() {
$.ajax('../find_paper.php', {
method: 'POST',
contentType: 'text'
}).done(function(ajaxData) {
this.paperData = $.parseJSON(ajaxData);
for (var i = 0; i < this.callbacks.length; i++)
this.callbacks[i](this.paperData);
}.bind(this));
}
};
var loader = new paperDataLoader();
var paper = new Paper();
loader.registerDataLoaded(paper.populate);
loader.loadData();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
'this'的值根據其上下文而變化。哪條線路遇到問題? – Halcyon
line with console.log – Flake