this指向 && 更改(call,apply,bind)

一、this指向

1. 普通函数

function fn1() {
    console.log(this) // window
}

而严格模式下, this为undefined

function fn2() {
  "use strict";
  return this;
}

fn2() === undefined; // true

2. 构造函数

function Person(name, sex) {
  this.name = name
  this.sex = sex
  console.log(this)  // this指向 Person 的实例对象 p
}
  
let p = new Person(18, '阴阳')

3. 对象方法

a.函数的定义位置不影响其this指向,this指向只和调用函数的对象有关
b.多层嵌套的对象,内部方法的this指向被调用函数最近的对象

let obj = {
    name: 'li',
    getName() {
        console.log(this.name) // this指向obj
    },
    innerObj: {
        name: 'son',
        getSonName() {
            console.log(this.name) // this指向innerObj
        }
    }
}
obj.getName()

4. 事件绑定

let oBtn = document.getElementById("btn-box")

oBtn.onclick = function() {
    console.log(this); // btn
}

5. 箭头函数

由于箭头函数不绑定this, 它会捕获其所在(定义的位置)上下文的this值, 作为自己的this值;下图可以看到,箭头函数在setTimeout中的this指向了构造函数新生成的对象,而普通函数指向了全局window对象

二、修改this指向

1. call

call(thisScope, arg1, arg2, arg3...)

2. apply

apply(thisScope, [arg1, arg2, arg3...]);两个参数

apply() 与call()非常相似,不同之处在于提供参数的方式,apply()使用参数数组,而不是参数列表

3. bind

bind改变this指向后,返回的是函数

let info1 = {
    name: "小sun",
    gender: 0,
    age: 24,
    say: function(looks, grade) {
       console.log(this.name, this.gender, this.age)                                
    }
}

let info2 = {
  name: "小李",
  gender: 1,
  age: 18
}

info1.say.call(info2 ,"小帅哥","大班") 
info1.say.apply(info2 ,["小帅哥","大班"])
info1.say.bind(info2)("小帅哥","大班")

// this原先指向info1,现在指向info2

相似处
    1、第一个参数都是this要指向的对象。
    2、都可以利用传参。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值