一.普通函数
方法是谁调用的,this就指向谁,如果没有元素调用,那么this会指向window
{//有元素调用函数
let obj = {
name: "obj",
fn: function () {
console.log(this);//obj
}
};
obj.fn();
}
{//没有元素调用函数
function fn() {
console.log(this);//window
}
fn();
}
二.构造函数
构造函数中的this指向实例本身
function Fn(name){
this.name = name;
this.age = 18;
console.log("Fn中的this==>",this); //new Fn()
}
Fn.prototype.sayName = function(){
console.log(this.name);
console.log(this)
}
let fn = new Fn("哈哈");
fn.sayName() //哈哈 Fn {name: '哈哈', age: 18}
console.log(fn); //Fn {name: '哈哈', age: 18}
三.对象函数
在对象函数中调用,this就是当前对象
window.b=2222
let obj={
a:111,
fn:function(){
alert(this.a);//111
alert(this.b);//undefined
}
}
obj.fn();
四.构造函数
构造函数中的this指向实例本身(实例化出来的对象)
function Fn(name) {
this.name = name;
this.age = 18;
console.log("Fn中的this==>", this); //new Fn()
}
Fn.prototype.sayName = function () {
console.log(this.name); //new Fn()
console.log("sayName中的this==>", this);
};
let fn = new Fn("哈哈");
fn.sayName();
console.log(fn);
五.箭头函数
箭头函数中的this指向箭头函数父级的上下文
let obj = {
name: "obj",
fn: function () {
console.log(this); //obj
let fn2 = () => {
console.log("箭头函数 fn2 中的this指向=========>", this); //obj
};
fn2();
},
};
obj.fn();
六.call,apply和bind
如果用call、apply、bind调用函数,这三个函数的第一个参数就是this指向,但是这三个参数不能改变箭头函数的this指向
-
call(arg, arg2, args, ...)
-
第一个参数:this指向
-
call方法从第二个参数起是一个参数列表
-
原函数立即执行
-
-
apply(arg, arg2)
-
第一个参数:this指向
-
第二个参数:数组或者伪数组
-
原函数立即执行
-
-
bind(arg, args2)
-
第一个参数:this指向
-
第二个参数:数组或者伪数组,可以分多次传参
-
返回的是一个函数,原函数不立即执行
-