我试图创建一个小的JavaScript插件这样的:this.welcome()不是一个函数
function TextShadow(host){
this.host_id=host;
this.welcome=function(){alert('welcome to earth')};
$(function(){
this.welcome();
$(this.host_id).html("<p>hello world</p>");
});
}
我再从其他脚本中调用它像这样:
var test=new TextShadow("#sample");
但我得到this.welcome不是function.However如果我前面的代码更改为以下一个一切正常:
function TextShadow(host){
this.host_id=host;
this.welcome=function(){alert('welcome to earth')};
var gen=this;
$(function(){
gen.welcome();
$(gen.host_id).html("<p>hello world</p>");
});
}
钙有人向我解释为什么第一段代码在第二段代码不起作用的时候?
每个函数都有一个'this',这将取决于如何** **你调用该函数。请参阅http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – elclanrs
'this'不再指DOM Ready函数中的'TextShadow'实例:它正被用作引用窗口对象。 – Terry