this的指向问题

一.this的指向问题:谁调用函数,函数中的this就指向谁

function fun1() {
        console.log(this)
    }
fun1()

function fun1() {
        console.log(this)
    }
window.fun1()

两者结果一样,所以如果直接调用相当于window.xxx

const obj = {
        a: '1',
        b: fun1
    }
    function fun1() {
        console.log(this)
    }
obj.b() //是obj.b调用的fun1函数

 二.能改变this指向的有:new操作符,call,apply,bind,箭头函数

1.new操作符

function Wangcai() {
        console.log(this)
    }
const wc = new  Wangcai()

this本应该指向window,但是通过运用new操作符之后,this指向了Wangcai()这个对象 

2.call,apply,bind

function fun1() {
        console.log(this)
    }
    const obj1 = {
        name: 'aa',
        age: '28'
    }
fun1.call(obj1)
fun1.apply(obj1)

 call和apply都能改变this指向,并立即执行函数

function fun1() {
        console.log(this)
    }
const obj1 = {
        name: 'aa',
        age: '28'
    }
fun1().bind(obj1)

但是却没有输出任何东西

function fun1() {
        console.log(this)
    }
    const obj1 = {
        name: 'aa',
        age: '28'
    }
fun1().bind(obj1)()

 

 结论:call和apply都会立即执行函数,但是bind不是

①.call

const obj1 = {
        name: 'aa',
        age: '28'
    }
function fun1(a, b, c) {
        console.log(a)
        console.log(b)
        console.log(c)
    }
fun1.call(obj1, 'one', 'two', 'three') //one,two,three

②.apply

const obj1 = {
        name: 'aa',
        age: '28'
    }
function fun1(a, b, c) {
        console.log(a)
        console.log(b)
        console.log(c)
    }
fun1.apply(obj1, 'one', 'two', 'three')

const obj1 = {
        name: 'aa',
        age: '28'
    }
function fun1(a, b, c) {
        console.log(a)
        console.log(b)
        console.log(c)
    }
fun1.apply(obj1, ['one', 'two', 'three'])

由此可见,使用apply时,参数类型必须为数组,且数组中的每个元素都作为独立的个体,而call对参数类型没有限制。

③.bind

const obj1 = {
        name: 'aa',
        age: '28'
    }
function fun1(a, b, c) {
        console.log(a)
        console.log(b)
        console.log(c)
    }
fun1.bind(obj1, 'one', 'two', 'three')()
fun1.bind(obj1, ['one', 'two', 'three'] )()

 结论:bind方法对于参数类型没有限制,当参数为数组时,其为一个整体,数组内元素不分别独立。

总结:1.如果是普通函数调用,this指向window

2.如果是构造函数,也就是通过new调用,this指向构造函数当前new出来的实例

3.如果是对象调用函数,则this指向调用函数的对象

4.如果是使用call,apply,bind调用,则this就指向你手动在其后面设置的对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值