2016-02-28 109 views
1

我试图创建一个小的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>"); 
     }); 
    } 

钙有人向我解释为什么第一段代码在第二段代码不起作用的时候?

+0

每个函数都有一个'this',这将取决于如何** **你调用该函数。请参阅http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – elclanrs

+0

'this'不再指DOM Ready函数中的'TextShadow'实例:它正被用作引用窗口对象。 – Terry

回答

2

因为范围在JavaScript函数内发生变化。您可以使用bindthis设置为所需值的功能。

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

1

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

0

在你的第一个功能欢迎功能不能被看到,因为这绑定当前执行上下文的.anonymous功能是当前执行上下文,并尝试寿接入功能,形成花药方面

1

您可以使用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)); 
} 

OR

使用self或任何变量来存储this和场所使用selfthis

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