<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>this关键字</title>
</head>
<body>
<script>
/*知识点:
* 1.在 JavaScript 中 this的指向不是固定不变的,它会随着执行环境的改变而改变。
2.在方法中,this 表示该方法所属的对象。
3.如果单独使用,this表示全局对象。
4.在函数中,this表示全局对象。
5.在函数中,在严格模式下,this是未定义的(undefined)。
6.在事件中,this表示接收事件的元素。
7.类似 call() 和 apply() 方法可以将 this引用到任何对象。*/
// 严格模式的声明,必须在所有代码的第一行声明,否则,无效。
"use strict";
// 示例1.创建一个对象
let person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function () {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName());
// John Doe
// 示例2.单独使用 this,则它指向全局(Global)对象。
// 在浏览器中,window 就是该全局对象。
console.log("this:", this);
// this: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
//示例3.严格模式下,如果单独使用,this也是指向全局(Global)对象。
console.log("this:", this);
// this: Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
// 示例4.在函数中,函数的所有者默认绑定到this上。
// 在浏览器中,window 就是该全局对象。
// 注释调首行的"use strict";
function f() {
return this;
}
console.log("f():", f());
// f(): Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, parent: Window, …}
// 示例5.严格模式下函数是没有绑定到 this 上,这时候 this 是 undefined。
// 打开首行的"use strict";
function f2() {
return this;
}
console.log("f2():", f2());
// f2(): undefined
// 示例7.this 是 person 对象,person 对象是函数的所有者。
person = {
firstName: "John",
lastName: "Doe",
id: 5566,
myFunction: function () {
return this;
}
};
console.log(person.myFunction());
// {firstName: "John", lastName: "Doe", id: 5566, myFunction: ƒ}
// 示例8.显式函数绑定
// 在 JavaScript 中函数也是对象,对象则有方法。
// apply 和 call 就是函数对象的方法。
// 这两个方法异常强大,他们允许切换函数执行的上下文环境(context),即 this 绑定的对象。
// 在下面实例中,当我们使用 person2 作为参数来调用 person1.fullName 方法时,
// this 将指向 person2, 即便它是 person1 的方法
let person1 = {
fullName: function () {
return this.firstName + " " + this.lastName;
}
};
let person2 = {
firstName: "John",
lastName: "Doe",
};
let x = person1.fullName.call(person2);
console.log("x:", x);
// x: John Doe
// 参考:https://www.runoob.com/js/js-this.html
</script>
<!--示例6.在 HTML 事件句柄中,this 指向了接收事件的 HTML 元素。-->
<button onclick="this.style.display='none';">点我后,我就消失了</button>
</body>
</html><!DOCTYPE html>
<html>
<head>
<met