我很困惑與this
保留密鑰和案件造成的錯誤。這裏有一個示例代碼,它會導致錯誤。jQuery:保留密鑰本和模棱兩可的情況下
var sample = {
init: function() {
this.sampleFunction0();
this.sampleFunction1();
},
sampleFunction0 : function(){
var something0, something1, something2;
something0 = this.sampleFunction2(); // works, there is no ambiguity whit 'this'
jQuery('#list li').click(function(){
something1 = this.sampleFunction2(); // ambiguity: not works, but sample.sampleFunction2(); works
something1 = sample.sampleFunction2(); // it´s works
something2 = $(this).text(); // list item val
console.log(something0) // something
console.log(something1); // something : using sample.sampleFunction2();
console.log(something2); // item val
});
},
sampleFunction1 : function(){
return 'someting';
},
sampleFunction2 : function(){
return 'something';
}
}
jQuery(document).ready(function(){
sample.init();
});
我不知道,如果是正確使用sample.sampleFunction2();
代替this.sampleFunction2();
感謝您的回答和參考。我是JS和jQuery的新手,每天都很棒。 – Marcos
@Marcos:不用擔心,樂於幫忙。請享用! –