<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
/**
* this 作为JavaScript的关键字,经常容易混淆其所代表的值,现总结如下:
* 情况一:全局函数
* 全局函数中this指向的是global对象
*/
var x1 = 1;
function test1() {
console.log(this.x1);
}
test1(); //1
var y1 = 1;
function test2() {
this.y1 = 0;
}
test2();
console.log(this.y1); //0
/**
* 情况二:某个对象的方法
*/
function test3() {
console.log(this.x);
}
var o = {};
o.x = 1;
o.m = test3;
o.m(); //1
/**
* 情况三:作为构造函数
* 用new关键字,再调用function会生成一个新的对象,而this则指向这个对象
*/
function test4() {
this.x = 1;
}
var b = new test4();
console.log(b.x); //1
/**
* 情况四:apply 和 call 调用
* this将指向apply和call的第一个参数target
*/
function test5() {
console.log(this.x);
}
var j1 = {};
var j2 = {};
j1.x = 1;
j2.x = 2;
j1.m = test5;
j1.m.apply(j2); //2
j1.m.call(j2); //2
</script>
</head>
<body>
</body>
</html>输入结果:JavaScript this简介
最新推荐文章于 2020-07-18 15:08:08 发布
本文详细解析了JavaScript中this关键字在不同上下文中的行为表现,包括全局函数、对象方法、构造函数及通过apply和call调用的情况,并展示了相应的运行结果。
8148

被折叠的 条评论
为什么被折叠?



