面向对象语言中 this 表示当前 对象 的一个引用。但在 JavaScript 中 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>
程序运行后,控制台输出如下:
我们可以看到,在全局作用域中,我们判断 this 与 windows 相等,结果输出了 true,即,此时,this 就是 window。
最后,我们在全局定义了一个 name 变量,结果分别使用 this 和 window 访问该 name 变量,结果输出了相同的值。
在函数中,函数的所属者默认绑定到 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>
程序运行后,控制台输出如下:
我们可以看到,在函数中,我们判断 this 与 windows 相等,结果输出了 true,即,此时,this 就是 window。
最后,我们使用严格模式,此时我们直接输出了 this,此时 this 是 undefined。
在方法中,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>
程序运行后,控制台输出如下:
在方法中的 this,就表明的是当前对象。
面向对象语言中 this 表示当前对象的一个引用。但在 JavaScript 中 this 不是固定不变的,它会随着执行环境的改变而改变。