Welcome 微信登录

首页 / 脚本样式 / JavaScript / 详解Javascript中的this关键字

详解Javascript中的this关键字2013-10-15 Justany_WhiteSnow 请看下面的代码,最后alert出来的是什么呢?

var name = "Bob"; var nameObj ={ name : "Tom", showName : function(){ alert(this.name); }, waitShowName : function(){ setTimeout(this.showName, 1000); } };nameObj.waitShowName();
要解决这个问题我们需要了解Javascript的this关键字的用法。

this指向哪里?

一般而言,在Javascript中,this指向函数执行时的当前对象。

   In JavaScript, as in most object-oriented programming languages, this is a special keyword that is used within methods to refer to the object on which a method is being invoked.

   ——jQuery Fundamentals (Chapter 2), by Rebecca Murphey

值得注意,该关键字在Javascript中和执行环境,而非声明环境有关。

   The this keyword is relative to the execution context, not the declaration context.

我们举个例子来说明这个问题:

var someone = {name: "Bob",showName: function(){alert(this.name);}};var other = {name: "Tom",showName: someone.showName}other.showName();  //Tom
this关键字虽然是在someone.showName中声明的,但运行的时候是other.showName,所以this指向other.showName函数的当前对象,即other,故最后alert出来的是other.name。