在js中,如果用prototype的方式写面向对象的代码,会遇到this指针混乱的问题。
如:
scrollnews.prototype={
panel:"",
xmlsrc:"",
templatesrc:"scrollnews.html",
xml:" ",
html:"haha",
load:function(){alert(this.html)},
loadhtml:function(){
$.ajax({
type:"GET",
url:this.templatesrc ,
data:new Date().getSeconds(),
dataType:"html",
error:function(err){ },
success:function(html){
this.html=html;
}
});
},
};
其中第三个this就不是scrollnews了,而是调用Ajax时建立的匿名对象,即便把scrollnews中load函数传递给success(success:this.load),在实际运行时,第一个this也无法读取scrollnews中的html。
由此总结:JavaScript中的函数并不严格属于某一个对象,而是谁包含它,并且主动调用它,那函数中的this就指向谁。