🧁个人主页:个人主页
✌支持我 :点赞👍收藏🌼关注🧡
this关键字指向
🍕默认绑定
默认指向全局window对象,但是在严格模式下this默认为undefined
function test(){
console.log(this);
}
test()
//window
🍟隐式绑定
当调用对象中的方法时,因为方法在对象内,所以此时方法中的this即为对象
var test ={
name:'小明',
height:165,
weight:120,
detail:function(){
console.log('姓名'+this.name);
console.log('身高'+this.height+'厘米');
}
}
test.detail()
//姓名小明
//身高165厘米
//可以看出this指的是test对象
//相当于 this.name =》name =》'小明'
🌭硬绑定
通过call,apply方法来改变this指向
var testName = {
name:'小明',
sayName:function(){
console.log('第一位考生是'+this.name);
}
}
var test1 = {
name:'小白'
}
var test2 = {
name:'小红'
}
testName.sayName.apply(test1)
testName.sayName.call(test2)
//第一位考生是小白
//第一位考生是小红
//可以看出在使用apply时,this指向即为test1对象,使用call时this指向也发生了变化,指向了test2对象
🍿构造函数绑定
🎄将变量名实例化,此时this会和实例化后的新对象紧紧绑定在一起,这样即使出现同名的变量也不会有影响
补充
🍗fn.call()
通过call()可以使用另一个对象方法,即改变this
✨1. 将this关键字改为call方法的第一个参数
✨2. 获取call方法第二个及以后的参数
✨3. 执行要操作的函数,并把第二个及以后的参数传递给函数
🍠 fn.apply()
🎀和apply方法大致相同,但是第二个参数为一个数组,即call()分别接收参数,而apply()是将要传给fn的参数放在一个数组中
var person = {
fullName: function (city, country) {
console.log( this.firstName + " " + this.lastName + "," + city + "," + country);
}
}
var person1 = {
firstName: "Bill",
lastName: "Gates"
}
person.fullName.apply(person1, ["Oslo", "Norway"]);
//Bill Gates,Oslo,Norway