<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
//全局中this为window对象
console.log(this);
//函数内this指向window
var x = 1;
function test(){
console.log(this);
console.log(this.x);
}
function changeX(){
this.x=5;
}
changeX();
test();
//函数内部函数N次嵌套this还是指向window
var x = 1;
var s=function test(){
console.log(this.x);
inner();
function inner(){
console.log(this.x);
innerInner();
function innerInner(){
console.log(this);
console.log(this.x);
}
}
}
s();
//函数内外相同变量容易混淆
var x = 1;
var s=function test(){
var x=3;
console.log(x);
console.log(this.x);
}
s();
//构造函数中的this指向对象本身
var x = 1;
function test(){
console.log(this);
this.x=2;
}
var o=new test();
console.log(o.x);
console.log(x);
//闭包中的this指向window
var x = 1;
function test(){
console.log(this.x);
console.log(this);
this.x=2;
var m=function (){
this.x=4;
console.log(this);
console.log(this.x);
console.log("m");
}
return m;
}
test();
var o=new test();
console.log(o.x);
o();
console.log("x:"+x);
//在对象中的this,this变化后的值变化
function test(){
console.log(this);
console.log(this.x);
}
test();
var o = {};
o.x = 1;
o.m = test;
o.m();
//apply动态指定this
var x = 0;
function test(){
console.log(this);
console.log(this.x);
}
test();
var o={
x:1,
m:this.test
};
o.m.apply(o);
</script>
</body>
</html>