一、this指向
1、全局 --->window
console.log(this); //Window对象
2、事件 --->事件源
<body>
<button>this指向</button>
</body>
<script>
var btn = document.querySelector('button');
btn.onclick = function() {
console.log(this); // <button>this指向</button>
}
</script>
3、函数 --->谁调用指向谁,没有默认window,函数内严格模式为undefined
let People = {
name : '张三',
age : 18,
sex (){
console.log(this); // {name: '张三', age: 18, sex: ƒ}
setTimeout(function () {
console.log(this) // window对象
})
setTimeout(()=> {
console.log(this) // {name: '张三', age: 18, sex: ƒ}
})
}
}
People.sex()
function testThis(){
console.log(this); // window对象
}
testThis()
function testThis(){
'use strict'
console.log(this); // undefined
}
testThis()
4、箭头函数 --->定义时所处函数环境
let btn = document.querySelector('button');
btn.onclick = ()=>{
console.log(this); // window对象
}
let People = function(name) {
this.name = name;
this.age = 18;
this.sex = () => {
console.log(this); // People {name: '张三', age: 18, sex: ƒ}
}
}
let People1 = new People('张三');
People1.sex()
5、构造函数 --->实例对象
let People = function(name) {
this.name = name;
this.age = 18;
this.sex = function(){
console.log(this); // People {name: '张三', age: 18, sex: ƒ}
}
console.log(this); // People {name: '张三', age: 18, sex: ƒ}
}
let People1 = new People('张三');
People1.sex()
二、改变 this 指向的三个方法
JavaScript 的一大特点是,函数存在「定义时上下文」和「运行时上下文」以及「上下文是可以改变的」这样的概念。
1、call
要改变this指向的函数.call(想要this指向的对象, 参数1, 参数2, 参数3…)
function People(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
console.log(this); // a处
}
let People1 = {
name: '张三',
age: 18,
sex: '未知',
fun: function(){
console.log(this); // b处
}
}
People1.fun() // b处 {name: '张三', age: 18, sex: '未知', fun: ƒ}
People.call(People1, '李四',14,'男') // a处 {name: '李四', age: 14, sex: '男', fun: ƒ}
People1.fun() // b处 {name: '李四', age: 14, sex: '男', fun: ƒ}
2、apply
要改变this指向的函数.apply(想要this指向的对象, [参数1, 参数2, 参数3…])
function People(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
console.log(this); // a处
}
let People1 = {
name: '张三',
age: 18,
sex: '未知',
fun: function(){
console.log(this); // b处
}
}
People1.fun() // b处 {name: '张三', age: 18, sex: '未知', fun: ƒ}
People.apply(People1,['李四',14,'男']) // a处 {name: '李四', age: 14, sex: '男', fun: ƒ}
People1.fun() // b处 {name: '李四', age: 14, sex: '男', fun: ƒ}
3、bind
要改变this指向的函数.bind(想要this指向的对象, 参数1, 参数2, 参数3…)
不会调用函数,返回是函数
function People(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
console.log(this); // a处
}
let People1 = {
name: '张三',
age: 18,
sex: '未知',
fun: function(){
console.log(this); // b处
}
}
People1.fun() // b处 {name: '张三', age: 18, sex: '未知', fun: ƒ}
let People2 = People.bind(People1, '李四',14,'男') // 无
People2() // a处 {name: '李四', age: 14, sex: '男', fun: ƒ}
People1.fun() // b处 {name: '李四', age: 14, sex: '男', fun: ƒ}
4、三者区别
方法 | 参数 | 是否执行函数 | 返回值 |
call | 想要this指向的对象, 参数1, 参数2, 参数3… | 是 | 原函数定义的返回值 |
apply | 想要this指向的对象, [参数1, 参数2, 参数3…] | 是 | 原函数定义的返回值 |
bind | 想要this指向的对象, 参数1, 参数2, 参数3… | 否 | 新的函数 |