this的概念
this指的是函数执行时所在的作用域,就是谁调用this,this就指向谁
this的具体指向
1、在全局调用this的时候,this就指向window
<script>
console.log(this)
</script>
2、当一个函数被当成一个对象的方法调用时,this指向这个对象
var a = {
name:"a",
fun:function(){
return this
}
}
console.log(a.fun())
3、通过事件来调用时,this指向这个函数的调用者
<body>
<button>click</button>
</body>
<script>
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
console.log(this); //this
})
</script>
4、在构造函数中的this指向它的实例化对象
<script>
function Fun(name){
this.name = name;
}
var fun1 = new Fun("fun");
console.log(fun1)
</script>
5、箭头函数中没有自己的this,它的this是继承的,默认指向定义时的this,而不是执行时的this
6、改变this指向的call,apply,bind使用方法及区别
相同点:
1.都是用来改变函数的this对象的指向。
2.第一个参数都是this要指向的对象。
3.都可以利用后续参数传参
不同点:
call()方法可以传递两个参数。第一个参数是指定函数内部中this的指向,第二个参数是函数调用时需要传递的参数。
call方法中的第一个参数是必须的,可以是null,undefined,this,但是不能为空.
function AA(uname){
this.name=uname
}
function BB(){
this.sex="女";
AA.call(this,"武大狼"); // 相当于调用AA 构造函数 完成继承
}
var obj=new BB();
alert(obj.name)
apply()和call差不多,apply方法的第一个参数也是this所要指向的那个对象,如果设为null或undefined,则等同于指定全局对象。
只不过apply第二个参数必须传入的是一个数组,该数组的所有成员依次作为参数,传入原函数,而call 第二个参数可以是任意类型
call.()和apply.()格式:
call.(thisOject, arg1 ,arg2 …)
apply.(thisObject,[arg1,arg2…])
var a = {
name : "Cherry",
func1: function () {
console.log(this.name)
},
func2: function () {
setTimeout( function () {
this.func1()
}.apply(a),100);
}
};
a.func2() // Cherry
bind方法会创建一个新的函数,当被调用的时候,将其this关键字设置为提供的值,我们必须手动去调用。
var a ={
name : "Cherry",
fn : function (a,b) {
console.log( a + b);
console.log( this.name );
}
}
var b = a.fn;
b.bind(a,1,2)() //3 //Cherry