Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在javascript函数中创建一个超级_Javascript_Jquery - Fatal编程技术网

如何在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:在高度本地化的示例中。一般来说,这种模式不适用。