如何在javascript函数中创建一个超级
如本例所示:如何在javascript函数中创建一个超级,javascript,jquery,Javascript,Jquery,如本例所示: 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
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();
});
我怎样才能做到这一点呢?我在互联网上看到了很多例子(包括基于jQuery的),都使用了以下方法:
var that = this;
var sayName = function() {
alert(that.name);
}
还有另一种方法:
var teste = {name:'marcos'};
$(teste).each(function(){
var that = this;
var sayName = function(){
alert(that.name);
}
sayName();
});
那是你的超级:-)
说真的,没有“super”,因为它不是扩展。
这在JavaScript中从来都不是隐式的(就像在Java中一样)。这意味着,如果不将函数作为对象上的方法调用,此
将不会绑定到合理的对象(它将绑定到浏览器中的窗口
对象)。
如果您想在函数中包含一个this
,则应将该函数用作一种方法,即:
var teste = {name:'marcos'};
$(teste).each(function(){
this.sayName = function(){
alert(this.name);
}
this.sayName();
});
然后sayName是一个方法,在this
-1:这是OP的原始代码中调用。他在要求一个替代方案。-1:这是OP的原始代码。他在要求一个替代方案,这是不公平和错误的。他问:“我想访问这个函数中的‘this’”,在上面的一行,他演示了你的解决方案,并写道“我不想那样做”,我相信他说“我不想这样做‘name=this.name’”。不是所有人都知道可以将“this”存储到变量中,给我-1是不公平的。我认为很明显,他在寻找比设置变量更奇特的东西。如果您不这么认为,很抱歉。您可以安全地删除var name=…
并将alert(name)
替换为alert(this.name)
,我相信这是您的初衷。此外,它将sayName
添加到test
对象中,下一步每个也将计算sayName
,这不太好。@Tomalak Geret'kal试试看,它行得通<调用this.sayName()
时,code>this
内部函数与otside相同,即teste
对象。@Victor:在高度本地化的示例中。一般来说,这种模式不适用。