我以为我已经了解了 javascript 中的上下文和范围。我不明白为什么在一种情况下代理/绑定有效,而在另一种情况下却没有。请问有人可以解释吗?
示例 1:代理(或绑定)工作:
function Cat(name){
this.name = name;
$("#cat").click(
$.proxy(
function(e){ this.meow(e); }
, this)
);
this.meow = function(){ alert(this.name + "says meow"); }
}
var cat = new Cat();
示例 2:代理和绑定不起作用:
function Dog(breed){
this.breed = breed;
this.save = function(){
var that = this;
$.ajax({
url: '/ajax/savedog.php', dataType: 'json',
// This works?? Shouldn't scope be of .ajax()?
data: this.breed,
// success: $.proxy(... // won't work? why?
success: that.dogSaved, error: ajaxFail
});
};
this.dogSaved = function(){ alert("Dog Saved"); }
}
var dog = new Dog();