<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
</body>
<script>
window.onload = function () {
/**
* 全局作用域中 —— window
*/
a = 21;
console.log(this === window) // true
console.log(this.a) // 21
console.log(window.a) // 21
// 结论 :window
/**
* 函数上下文调用
*/
// 1. 非严格模式下 —— window
function fn() {
return this;
}
console.log(fn() === window); // true
// 2. 严格模式下 —— undefined
function fn2() {
"use strict";
return this;
}
console.log(fn2()); // undefined
// 结论 :非严格模式下函数中的this就是 window;严格模式下是 undefined
/**
* 对象中的 this
*/
var obj = {
age:20,
fun() {
return this.age;
}
}
console.log(obj.fun()); // 20
// window.age = undefined
var f = obj.fun;
console.log(f()); // undefined
// 结论 :指向方法所在的这个对象(window也是对象)
/**
* 原型链中的 this
* 原型链中的方法的 this 仍然指向调用它的对象
*/
/**
* 构造函数中的 this
*/
function Fun() {
this.name = 'Li';
}
var o = new Fun();
console.log(o.name); // Li
// 结论 : new 构造函数中的this指向新生成的对象
/**
* 箭头函数中的 this
*/
// 于普通函数来说,内部的this指向函数运行时所在的对象,但是这一点对箭头函数不成立。
// 它没有自己的this对象,/* 内部的this就是定义时上层作用域中的this */
// 也就是说,箭头函数内部的this指向是固定的,相比之下,普通函数的this指向是可变的。
}
</script>
</html>