谁调用函数this就指向谁:
1.普通函数调用时,this指向的是window;例如定义一个函数fun时,直接调用该函数时this指向的就是window。
function fn() {
console.log(this); // window
}
fn(); // window.fn(),此处默认省略window
2.构造函数调用,此时this指向的是实例对象。
function Person(age, name) {
this.age = age;
this.name = name
console.log(this)
// 此处 this 分别指向 Person 的实例对象 p1 p2
}
var p1 = new Person(18, 'zs')
var p2 = new Person(18, 'ww')
3.对象方法调用,this指向该方法所属对象.
var obj = {
fn: function () {
console.log(this); // obj
}
}
obj.fn();
4.通过事件绑定的对象,此时this指向的是绑定该事件的对象。例如按钮绑定点击事件,此时this指向的就是该按钮。
5.定时器函数, 此时 this 指向 window。
setInterval(function () {
console.log(this); // window
}, 1000);
6.立即执行函数的this指向window。
更改this指向有三个方法:
1.call()方法:.call(this指向对象,参数);
var Person = {
name: "lixue",
age: 21
}
function fn1(x, y) {
console.log(x + "," + y); //hh,20
console.log(this); //Window
}
fn1("hh", 20)
此时this指向window,现在用call来更改this指向。
var Person = {
name: "lixue",
age: 21
}
function fn1(x, y) {
console.log(x + "," + y) //hh,20
console.log(this) //Person
console.log(this.name) //lixue
console.log(this.age) //21
}
fn1.call(Person, "hh", 20)
现在this就指向person了。
eg2:
var o = {
name: 'andy'
}
function fn1() {
console.log(this.name)//andy
}
fn1.call(o) //call将this指向了对象o
2.apply()方法 .apply(this指向对象,[数组]);
apply() 与call()非常相似,不同之处在于提供参数的方式,apply()使用参数数组。
var o = {
name: 'andy'
}
function fn1(x, y) {
console.log(this.name) //andy
console.log(x + y); //14
}
fn1.apply(o, [5, 9]) //apply将this指向了对象o
3.bind()方法:不会调用函数,上面俩者都会调用函数。bind方法返回的是原函数改变this指向后产生的新函数。
var o = {
name: 'andy'
}
function fn1(x, y) {
console.log(this.name) //andy
console.log(x + y); //14
}
var fn2 = fn1.bind(o, 5, 9)
fn2()//返回的是原函数改变this指向后产生的新函数。