执行上下文this

this指向window的两种情况:1.new function 2.全局对象this

1
2
3
4
5
6
7
8
9
10
function func1(){
this.name = "jim";
console.log(this); //this 指向 window
}
function func2(){
console.log(this.name); //this 指向 window
}
func1();
func2();
console.log(this); //this 指向 window

通过构造器创建对象,this指向该创建的对象,如var harry = new Persion(‘Harry’,18,’female’),this指向harry对象

1
2
3
4
5
6
7
8
9
10
11
12
function Persion(name,age,sex){
this.name = name;
this.age = age;
this.sex = sex;
this.changeAge = function(age){
this.age = age;
console.log(this); //this 指向 harry对象
}
console.log(this); //this 指向 harry对象
}
var harry = new Persion('Harry',18,'female');
harry.changeAge(22);