this的概念:
在JavaScript中,this是一个关键字,它指向当前执行代码的上下文对象。具体来说,this的指向取决于函数的调用方式。在全局作用域中,this指向全局对象window;在函数内部,this指向调用该函数的对象;在构造函数中,this指向新创建的对象;在事件处理函数中,this指向触发事件的元素。此外,在箭头函数中,this指向定义该函数时所在的作用域。
一、全局作用域中的this
// 全局作用域下的this指向
console.log(this);//window
二、函数中的this
// 函数中的this指向
function fun(){
console.log(this);//this指向window对象
}
fun()
三、对象中的this
// 对象中的this指向
var obj = {
fun: function () {
console.log(this);
}
}
obj.fun()//this指向obj
四、箭头函数中的this
箭头函数:this指向于函数作用域所用的对象。
五、改变this指向的方法
1. call()
调用函数,可以改变函数的this指向,如果没有参数,this就指向window,如果加一个参数,this就指向该参数,如果参数为多个参数,this指向第一个参数,后面所有参数为参数列表。
如:
var person = {
name: 'Tom',
sayHello: function() {
console.log('Hello, ' + this.name);
}
};
var anotherPerson = {
name: 'Jerry'
};
person.sayHello.call(anotherPerson); // 输出:Hello, Jerry
2. apply()
apply()方法与call()方法类似,只是传递参数的方式不同。apply()方法的第一个参数是要指向的对象,第二个参数是一个数组,数组中的元素是传递给函数的参数。
如:
function fn (n1,n2){
console.log(this);
console.log(n1,n2)
console.log(arguments)
}
let obj = {fn:fn};
fn.applay(abj,[11,'apply',{a:123}]);//第二个参数必须是数组,否则会报错
3. bind()
会创建一个新的函数,新函数与旧函数的函数体内容一模一样,区别在与新函数this指向被修改了。
如:
var person = {
name: 'Tom',
sayHello: function() {
console.log('Hello, ' + this.name);
}
};
var anotherPerson = {
name: 'Jerry'
};
let sayHelloToAnotherPerson = person.sayHello.bind(anotherPerson);
sayHelloToAnotherPerson(); // 输出:Hello, Jerry