gpt4 book ai didi

javascript - 为什么在这一行中需要 bind(this) ?

转载 作者:行者123 更新时间:2023-11-29 18:24:37 24 4
gpt4 key购买 nike

我在这里关注谷歌浏览器的扩展开发指南: 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);
},

,他们使用了这样的绑定(bind)函数this.showPhotos_.bind(this);如果没有这个绑定(bind),示例扩展将无法工作。我在 showPhotos_ 方法中进行了测试,并验证了“this”只是 kittenGenerator 对象。由于 showPhotos_ 只是该对象的一个​​方法,这应该是隐式完成的,那么为什么仍然需要这种绑定(bind)?


请注意,由于 popup.js 文件中的拼写错误,google 的示例将无法运行。要更正它,请将“kittensOnFlickr_”更改为“searchOnFlickr_”。

最佳答案

如果从 req.onload 调用时没有绑定(bind) showPhotos_this 将是 req 而不是 kittenGenerator

关于javascript - 为什么在这一行中需要 bind(this) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14801671/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com