this引用的是函数执行的环境对象
调用函数之前,this的值并不确定,因此this可能会在代码执行过程中引用不同的对象
函数的名字仅仅是一个包含指针的变量而已。因此,即使是在不同的环境中执行,全局的sayColor()函数与o.sayColor()指向的仍然是同一个函数。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<!-- 函数的名字仅仅是一个包含指针的变量而已。
因此,即使是在不同的环境中执行,
全局的sayColor()函数与o.sayColor()指向的仍然是同一个函数。
-->
<!-- 调用函数之前,this的值并不确定,因此this可能会在代码执行过程中引用不同的对象 -->
<!-- this引用的是函数执行的环境对象 -->
<script>
window.color = "red";
var o = { color: "blue" };
o.sum = sum;
o.sum(); //blue
function sum() {
console.log(this.color);
}
sum(); //red
//自执行函数的的this
(function sum() {
console.log(this); //Window {window: Window, self: Window, document: document, name: "", location: Location, …}
})();
</script>
</body>
</html>