2011-07-06 26 views
8

像一个超级例:如何使JavaScript函数

var teste = {name:'marcos'}; 
$(teste).each(function(){ 

    var name = this.name; // i don't want to do that. 

    // i want to have access to 'this' inside this function (sayName) 
    var sayName = function(){ 
     alert(name); // there is something like "super" in java? or similar way to do? 
    } 
    sayName(); 

}); 

我怎样才能做到这一点?

回答

0

我看到了很多的互联网的例子(jQuery的基于含)使用此:

var that = this; 
var sayName = function() { 
    alert(that.name); 
} 
+0

-1被调用:这是OP的原始代码。他正在寻求替代方案。 –

+0

这是不公平的错误。他问道:“我想要在这个函数中访问'this' –

+0

并且在上面这行中,他演示了你的解决方案并写道”我不想那样做“ –

-1

这里是另一种方式:

var teste = {name:'marcos'}; 
$(teste).each(function(){ 

var that = this; 

var sayName = function(){ 
    alert(that.name); 
} 
sayName(); 

}); 

那是你的超级:-) 严重,没有“超级”,因为它不是扩展名。

+0

-1:这是OP的原始代码。他正在寻求替代方案。 –

2

this从不隐含在JavaScript中(因为它在Java中)。这意味着如果你没有调用函数作为对象的方法,this将不会被绑定到合理的东西(它将被绑定到浏览器中的window对象)。 如果你想有一个this里面的功能,该功能应作为一个方法,那就是:

var teste = {name:'marcos'}; 
$(teste).each(function(){ 

    this.sayName = function(){ 
     alert(this.name); 
    } 
    this.sayName(); 

}); 

然后sayName是一种方法和this

+0

您可以安全地移除'var name = ...'并用'alert(this.name)'替换'alert(name)',我相信这是初衷。此外,它将'sayName'添加到'test'对象,并且接下来的'each'也将对'sayName'进行计数,这并不好。 –

+0

@Victor:不,你不能。 –

+0

@Tomalak Geret'kal试试看,它的工作原理。调用'this.sayName()'时,'this'里面的函数与otside相同,即'teste'对象。 –

相关问题