为什么在这一行中必须绑定(this)?

时间:2013-02-10 19:26:20

标签: javascript

我在这里关注google chrome的扩展程序开发指南: http://developer.chrome.com/extensions/getstarted.html

在此档案的第41行:http://sprunge.us/NFjZ

requestKittens: function() {
  var req = new XMLHttpRequest();
  req.open("GET", this.searchOnFlickr_, true);
  req.onload = this.showPhotos_.bind(this);
  req.send(null);
},

,他们使用像这样的绑定功能 this.showPhotos_.bind(本);如果没有此绑定,示例扩展将不起作用。我在showPhotos_方法中测试并验证“this”只是kittenGenerator对象。由于showPhotos_只是该对象的一种方法,因此应该隐式完成,所以为什么这种绑定必要呢?


请注意,由于popup.js文件中存在拼写错误,因此google的示例无效。 要更正它,请将“kittensOnFlickr_”更改为“searchOnFlickr _”。

1 个答案:

答案 0 :(得分:4)

从req.onload调用时没有绑定showPhotos_thisreq而不是kittenGenerator

相关问题