2015-09-01 57 views
1

在下面的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>

+0

'this'的值根据其上下文而变化。哪条线路遇到问题? – Halcyon

+0

line with console.log – Flake

回答

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地方?

+0

我存储paper.populate在一个paperDataLoader.callbacks数组中,然后当ajax请求成功时调用.done()方法 – Flake

+0

尝试调用paper.populate就像我有 – Flake

相关问题