JS中函数的分类
- 普通函数
- 构造函数
- 定时器中的函数
- 方法中的函数
- 绑定事件监听的函数
- 立即执行函数
默认情况下六大函数中this指向
普通函数(命名函数): this指向window
function fu(){
console.log("普通函数的this指向"+this);
}
fu()
函数表达式
const fun=function (){
console.log(“普通函数的this指向”+this);
}
构造函数:this指向对象s
function Star(){
console.log("构造函数的this指向"+this);
};
var s=new Star();//this指向s
定时器中的函数:this指向window
setTimeout(function(){
console.log("回调函数中的this指向"+this);
},1000)
方法中的函数:this指向o
var o={
say:function(){
console.log("方法中函数的this指向"+this);
}
}
绑定事件监听的函数:this指向按钮btn
var btn=document.querySelector("button")
btn.onclick=function(){
console.log("绑定事件监听函数的this"+this);
}
立即执行函数:this指向window
(function (){
console.log("立即执行函数的this指向"+this);
})()
改变函数中this指向
- call
- apply
- bind
1.call可以调用函数
call
var obj={name:"sdf"}
function fun(a,b){
console.log(this);
console.log(a+b);
}
fun.call() //调用函数
2.call改变函数内的this指向
var obj={name:"sdf"}
function fun(a,b){
console.log(this);
console.log(a+b);
}
fun.call(obj,1,2)
3.call的主要作用是用于继承
function Father(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}
function Son(name,age,sex){
Father.call(this,name,age,sex)//括号里面的this是son的这里是father中的this指向改变成son的
}
var son=new Son("li",1,"male")
console.log(son);
apply指向 apply() 与call() 非常相似, 不同之处在于提供参数的方式, apply() 使用参数数组, 而不是参数列表
var obj={name:"zhangsan"}
function fun (x,y){
console.log(this);
console.log(x+","+y);
console.log(this.name);
}
fun.apply(obj,[4,5])
bind指向 不会调用原来的函数,可以改变原来函数的this指向,返回的原函数改变this指向的新函数。
var obj={name:"zhangsan"}
function fun(){
console.log(this);
}
//fun.bind(obj)不会调用
fun.bind(obj)()
在项目中我们大多数情况下是不想调用函数指向改变函数中的this指向。比如按一下按钮,按钮失效3s后重新有效。(就像发验证码一样)
var btn=document.querySelector("button")
btn.onclick=function(){
this.disabled=true
setTimeout(function(){
this.disabled=false
}.bind(this),3000)
}
匿名函数中this指向问题
在函数被作为某个对象的方法调用时,this等于这个对象。
但是匿名函数的this是window, 如果要修改匿名函数的this指向,可以使用这样的办法。
var name = 'window'
var person = {
name :'Alan',
sayName:function () {
return function () {
console.log(this.name)
}
}
}
person.sayName()() // window
如下所示,使用that变量
var name = 'window'
var person = {
name :'Alan',
sayName:function () {
var that = this
return function () {
console.log(that.name)
}
}
}
person.sayName()() // Alan
箭头函数中this指向问题
箭头函数中没有this,没有anguments super()
绑定规则:绑定离自己最近的非箭头函数作用域里的this
var obj={
name:"zhangsan",
sayHello:function(){
setTimeout(()=>{console.log(this);},1000)
}}
obj.sayHello()//this指向obj