this.welcome() 不是函数

this.welcome() is not a function

我正在尝试创建一个像这样的小 javascript 插件:

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 is not a 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>");
        });
   } 

有人能解释一下为什么第一段代码不起作用而第二段代码起作用吗?

因为范围在 JavaScript 函数内发生了变化。您可以 bind 函数将 this 设置为所需的值。

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>");
    }.bind(this));
 }

它在 ES6 中更干净,您可以在其中使用 arrow functions:

$(() => {
  this.welcome();
  $(this.host_id).html("<p>hello world</p>");
});

MDN Scope

因为一旦进入匿名函数,您的 this 就会发生变化。通过将 this 分配给其他东西:gen,您仍然可以在不同的函数中使用它。

在您的第一个函数中,欢迎函数无法看到,因为 this 当前执行上下文的绑定。匿名函数是当前执行上下文,您尝试从花药访问函数上下文

您可以使用bind设置this

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>");
}.bind(this));
}



使用self或任何变量来存储this并使用self代替this

function TextShadow(host){
var self=this;
self.host_id=host;
self.welcome=function(){alert('welcome to earth')};
$(function(){
  self.welcome();
  $(self.host_id).html("<p>hello world</p>");
});
}