前端那些事

vuePress-theme-reco chenpeng    2020 - 2021
前端那些事 前端那些事

Choose mode

  • dark
  • auto
  • light
首页
文章目录
  • Browser
  • CSS
  • ES6
  • JavaScript
  • Network
  • TypeScript
  • Vue
  • Vue3
  • Webpack
标签
时间轴
GitHub
author-avatar

chenpeng

85

Article

25

Tag

首页
文章目录
  • Browser
  • CSS
  • ES6
  • JavaScript
  • Network
  • TypeScript
  • Vue
  • Vue3
  • Webpack
标签
时间轴
GitHub
  • JS-API

    • new的原理
    • new和Object.create的区别
    • bind、call、apply的区别
    • 如何正确判断this的指向
    • 深拷贝与浅拷贝

如何正确判断this的指向

vuePress-theme-reco chenpeng    2020 - 2021

如何正确判断this的指向

chenpeng 2020-11-30 JS API

this:谁调用它,this 就指向谁

# 1.普通函数

this 指向 window,严格模式下('use strict')会抛出错误 undefined

// 'use strict';
var name = '张三';
function fn() {
    console.log(this.name);
}
fn();// 张三
1
2
3
4
5
6

# 2.对象函数

this 指向该函数所属对象

var obj = {
    sayHello(){
        console.log(this);
    }
}
obj.sayHello();
// {sayHello: f}
1
2
3
4
5
6
7

# 3.构造函数

如果构造函数没有返回对象,则 this 指向创建的对象实例;如果构造函数有返回对象,则 this 指向返回的对象

function Person(name, age) {
    this.name = name;
    this.age = age;
}
var p = new Person('张三', 20);
console.log(p);
// Person {name: "张三", age: 20}
1
2
3
4
5
6
7
function Person(name, age) {
    this.name = name;
    this.age = age;
    let obj = {
        name: '赵四',
        age: 18
    };
    return obj;
}
var p = new Person('张三', 20);
console.log(p);
// {name: '赵四', age: 18}
1
2
3
4
5
6
7
8
9
10
11
12

# 4.绑定事件函数

this 指向事件的调用者

var btn = document.querySelector('button');
btn.onclick = function () {
    console.log(this);
}
// <button>点击</button>
1
2
3
4
5

# 5.定时器函数

this 指向 window

setTimeout(function () {
    console.log(this);
},1000);
1
2
3

# 6.立即执行函数

this 指向 window

(function() {
    console.log(this);
})();
1
2
3

# 7.箭头函数

不绑定 this,this 指向函数定义位置的上下文

btn.onclick = function () {
    setTimeout(() => {
        console.log(this);
        // <button>点击</button>
    },1000)
}
// 通过箭头函数可以改变定时器函数的this指向
1
2
3
4
5
6
7

# 8.显式绑定

函数通过 call()、apply()、bind()方法绑定,this 指向方法中传入的对象

function fn() {
    console.log(this);
}
var person = {
    name: '张三'
};
fn.call(person);
fn.apply(person);
fn.bind(person)();
// {name: '张三'}
1
2
3
4
5
6
7
8
9
10

如果这些方法中传入的第一个参数是 undefined 或 null,严格模式下 this 指向传入的值 undefined 或 null;非严格模式下 this 指向 window

function fn() {
    console.log(this);
}
fn.call(null);// window
1
2
3
4
'use strict';
function fn() {
    console.log(this);
}
fn.call(null); // null
1
2
3
4
5

# 9.隐式绑定

函数的调用是在某个对象上触发的,即调用位置存在上下文对象(相当于对象函数中的 this 指向)典型的隐式绑定为 xxx.fn()

function fn() {
    console.log(this.name);
}
var person = {
    name: '张三',
    fn
};
person.fn(); // 张三
1
2
3
4
5
6
7
8