<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var obj = {
m: function () {
var _self = this;
console.log(this + "this1");//[object Object]this1
console.log(this === obj);//true
inner();
function inner() {
var _that = this;
console.log(this + "this2");//[object Window]this2
console.log(this === obj);//false
console.log(_self === obj);//true
console.log(this === window);//true
inner2();
function inner2() {
console.log(this);//window
console.log(this === window);//true
console.log(_that === this);//true
inner3();
function inner3() {
console.log(this);//window
console.log(this === window);//true
}
}
}
}
};
obj.m();//obj调用的m(),所以在m()中的最外层中的this指的就是调用它的obj对象;但是在嵌套函数中,this不具有继承性,所以内部的其他函数中的this不在是obj对象,而是window对象
</script>
</body>
</html>
JavaScript函数中的this(函数嵌套时不具有继承性)
最新推荐文章于 2024-07-19 15:13:24 发布