this的七种指向问题
- 普通函数中,this指向window
function fn() {
console.log(this);
}
fn();
- 构造函数中,this指向实例化对象
function Person(age, name) {
this.age = age;
this.name = name
console.log(this)
}
var p1 = new Person(18, '张三')
var p2 = new Person(18, '李四')
console.log(p1)
console.log(p2)
- 对象函数中,this指向当前的对象
var obj = {
fn: function () {
console.log(this);
}
}
obj.fn();
- 事件函数中,this指向事件源
btn.onclick = function() {
console.log(this);
}
- 在定时器函数中this指向window
setInterval(function () {
console.log(this);
}, 1000);
- 原型对象的函数中:
a. 如果是实例对象调用,this指向实例对象 function Person(name,age){
this.name = name;
this.age = age;
console.log("输出");
console.log(this);
}
Person.prototype.hobby = function(){
console.log("输出");
console.log(this);
}
var per = new Person("小明",20);
per.hobby();
b. 如果是原型对象调用,this指向原型对象function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.hobby = function(){
console.log("理解性学习");
}
function Student(sex){
this.sex = sex;
}
Student.prototype.like = function(){
console.log("打篮球");
}
Student.prototype = new Person("小明",20);
var stu = new Student("男");
console.dir(stu);
stu.hobby();
- 在数组函数中,this指向当前数组
var name_1 = "小明";
function obj(){
var name_1 = "小红";
console.log(this);
console.log(this.name_1);
console.log(this[0].name_1);
}
var arr = [{name_1:"我是arr[0]的name"},obj];
arr.name_1 = "我是arr的name";
arr[1]();