1.第一种:单独存在的this
var x = this;
console.log(x);//window
(1) 在单独使用时,this指的就是全局对象也就是window
(2) 在严格模式下,this也指向window对象
2.函数中的this
function fun() {
console.log(this); // 打印 window 对象
console.log(this.name); // 打印 "全局的name属性"
}
var name = "全局的name属性";
fun();
函数中的this指向的也同样是window
3.方法中的this
var person = {
firstName:"Bill",
lastName:"Gates",
id:678,
fullName:function(){
return this.firstName + " " + this.lastName;
}
};
方法中的this指向这个方法的调用者
构造函数中的this
// 创建一个构造函数,专门用来创建Person对象
function Person(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
this.sayName = function() {
console.log(this.name); // 打印 "孙悟空"
};
}
var per = new Person("刘", 18, "男");
per.sayName()
this 指向新创建的那个对象