在下面的javascript代码中,我想知道哪个对象有"这个"指向。但我得到了一个功能。
我想"这个"总是提到调用该函数的对象。 所以有人能解释为什么会出现这种情况吗?
$(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();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 0 :(得分:1)
它为我工作:
var Paper = function() {};
Paper.prototype = {
populate: function(data) {
data.questions.forEach(function(entry) {
console.log(this);
}.bind(this));
}
};
var paper = new Paper();
paper.populate({ questions: [ 1 ] }); // prints paper object
也许你在某个地方重新绑定paper.populate
?