JavaScript this

JavaScript this教程

面向对象语言中 this 表示当前 对象 的一个引用。但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。

JavaScript this特点详解

  1. 函数 在定义的时候 this 是不确定的,只有在调用的时候才可以确定。
  2. 一般函数直接执行,内部 this 指向全局 window,在严格模式下,this 是 undefined
  3. 函数作为一个对象的方法,被该对象所调用,那么 this 指向的是该对象。
  4. 构造函数中的 this 其实是一个隐式对象,类似一个初始化的模型,所有方法和属性都挂载到了这个隐式对象身上,后续通过 new 关键字来调用,从而实现实例化。

案例

全局中的this

全局中的 this,表示是当前 window 对象

<!DOCTYPE html> <html> <head> <title>JavaScript全局this</title> <script type="text/javascript"> console.log("嗨客网(www.haicoder.net)"); console.log("this === window: ", this === window); var name = "HaiCoder"; console.log("this.name =", this.name, "windows.name =", window.name); </script> </head> </html>

程序运行后,控制台输出如下:

29_JavaScript this.png

我们可以看到,在全局作用域中,我们判断 this 与 windows 相等,结果输出了 true,即,此时,this 就是 window。

最后,我们在全局定义了一个 name 变量,结果分别使用 this 和 window 访问该 name 变量,结果输出了相同的值。

函数(function)中的this

在函数中,函数的所属者默认绑定到 this 上

<!DOCTYPE html> <html> <head> <title>JavaScript函数中的this</title> <script type="text/javascript"> console.log("嗨客网(www.haicoder.net)"); function func(){ console.log(this === window); } function sfunc(){ "use strict"; console.log(this); } func(); sfunc(); </script> </head> </html>

程序运行后,控制台输出如下:

30_JavaScript this.png

我们可以看到,在函数中,我们判断 this 与 windows 相等,结果输出了 true,即,此时,this 就是 window。

最后,我们使用严格模式,此时我们直接输出了 this,此时 this 是 undefined。

对象的this

在方法中,this 表明当前对象

<!DOCTYPE html> <html> <head> <title>JavaScript方法中的this</title> <script type="text/javascript"> console.log("嗨客网(www.haicoder.net)"); var obj = { foo: "bar", logFoo: function () { console.log(this.foo); } }; obj.logFoo(); </script> </head> </html>

程序运行后,控制台输出如下:

31_JavaScript this.png

在方法中的 this,就表明的是当前对象。

JavaScript this总结

面向对象语言中 this 表示当前对象的一个引用。但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。