this指向 apply/call() 可以把 this 引用到任意对象
this关键词指的是它所属的对象 => [谁调用指向谁]
方法中, this 指的是所属者对象; example:
const person = {
firstName: "Bill",
lastName : "Gates",
id : 678,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
// 创建的过程首先new Object()实例, 再赋值, 于是person就有了隐式原型;
// this指向person;
单独情况下 this 指向全局 window 对象 example:
- const x = this; // this是全局对象[Object window]
在函数中 this 也是全局 window 对象
- function a() {console.log(this)} => 输出[Object window]
- Remark JS严格模式下, 函数中的 this 为undefined
- function a() {
'use strict'; // 严格模式
console.log(this); // 输出undefined
}
在事件中, this 指的是接受事件的元素;
- example: button onclick="this.style.display = 'none'" 点击删除 /button
this 绑定方法: 对象绑定和显式 apply/call() 绑定;
对象绑定法
const person = {
age: 18,
sex: '男',
name: 'Boolean',
speak: function() {
return this;// this代表speak函数拥有者person;
},
};
显式绑定法 apply/call();
- apply/call()都是JS预定义的方法, 他们都可以用于将一个对象作为参数调用对象方法
- FOR example
const person1 = {
nameFunction: function() {
return this.name + this.sex + this.age + '岁';
},
};
const person2 = {
age: 20,
sex: '女',
name: 'Alone'
};
person1.nameFunction.call(person2);// 把函数nameFunction的this指向替换成person2;
箭头函数中的 this
与常规函数相比较箭头函数里面没有 this 的绑定
在常规函数中,关键字 this 表示调用该函数的对象,可以是窗口、文档、按钮或其他任何东西。
对于箭头函数中的 this 始终表示定义箭头函数的对象
总结:this 谁调用指向谁