欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

this 对象中的 Javascript 匿名函数介绍

最编程 2024-03-11 17:53:52
...


        在一般情况下,this对象时在运行时基于函数的执行环境绑定的:在全局函数中,this等于window,而当函数被作为某个对象的方法调用时,this等于那个对象。但是,匿名函数的执行环境具有全局性,因此它的this对象通常指向windows.

        看下面一段代码:

var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
};
}
};
alert(object.getNameFunc()()); //"The Window"(在非严格模式下)

       因为在getNameFunc()函数中,返回的是一个匿名函数,而在匿名函数中的return this.name语句中,this指的是全局环境中的window,因而结果为"The Window"那么,如果我们想要使得匿名函数中的this,指向的是当前的Object对象,应该如何处理呢。可以在匿名函数外声明一个变量,将this赋给变量,因为在匿名函数外的this就等于该对象。代码如下:

var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
var that=this;
return function(){
	return that.name;
};
}
};
alert(object.getNameFunc()());//The Object

这样就达到了我们的目的了,结果为My Object。当然了,上文在很大程度上,是为了说明,匿名函数中this的特殊性,如果只是想得到对象中变量的值,最简单的一种方法就是:

var name = "The Window";
var object = {
name : "My Object",
getNameFunc :function(){
	return this.name;
}
};
alert(object.getNameFunc());//The Object


       

   




推荐阅读