ozz*_*ozz 16 javascript json knockout.js
为什么我们不能直接使用this而不是self在以下示例中?
function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
}
Run Code Online (Sandbox Code Playgroud)
回答后,我了解到:
是的,没有必要在课堂上没有上下文切换.
但我会将这种方法用作"惯例",尽管没有必要.
Mat*_*att 26
有没有理由,你为什么不能使用this直接出现(我想说,如果你会为可读性更好做了).
但是,在var self = this;以下情况下经常需要(基本上,任何异步操作,如事件绑定,AJAX处理程序等,其中解析this延迟到等于其他东西);
function SeatReservation(name, initialMeal) {
var self = this;
self.name = name;
self.meal = ko.observable(initialMeal);
setTimeout(function () {
alert(self.name); // otherwise, this is window; use self to keep a reference to the "SeatReservation" instance.
}, 100);
}
Run Code Online (Sandbox Code Playgroud)
通常这样做是为了在上下文发生变化时保持对此的引用.它通常用于事件处理程序或回调函数.但如前所述,没有理由在您的具体示例中使用它.
您将在以下文章中找到更多详细信息:http://www.alistapart.com/articles/getoutbindingsituations
| 归档时间: |
|
| 查看次数: |
8228 次 |
| 最近记录: |