04_this指向

this

this 一般指当前调用的对象

this 一般来说 指向调用他的那个对象 谁调用他 指向谁

this 4种绑定规则

1. 默认绑定

对象调用内部函数 this 就是这个对象
全局调用 浏览器中 是winodw
node 是一个 {}

2. 隐式绑定
function foo() { console.log(this) }
foo()
var obj1 = { foo: foo }

var obj2 = { obj1: obj1 }
obj1.foo() // foo
obj2.obj1.foo() // foo 
3 显示绑定

apply call 参数不同 apply 为数组 call 为参数列表
bind

call(null)
apply(undefined)
bind(null)
// 传入 null 或者 undefined 的时候 会自动忽略
4 new

通过new 对象 新对象会绑定到函数调用的this上

绑定优先级  显示大于隐式  new 高于 隐式 高于 bind

间接函数 引用 拿到这个对象中的 函数 函数作为的是返回值 然后直接调用 this 会指向函数本身内部的this 通常可能为 window
箭头函数 不能绑定 this 不能通过new 实例调用

call

call 是在函数调用的时候的一个方法 可以传入 this
// 函数上的方法
Function.prototype.mycall = function(thisArg,...arg) { // 第一个参数为 this 指向的对象  后面可以传入任意参数 

    const Fn = this
    // this 指向调用这个方法的函数  Fn 代表这个函数

    // 绑定必须为对象 如果为 null || undefined 的话 还是指向 window
    thisArg = (thisArg !== null && thisArg !== undefined) ?
    Object(thisArg) : window

    // 调用执行的参数
    // 隐式绑定 让需要绑定的 this 来执行
    thisArg.fn = Fn  // 给这个this指向的对象添加 Fn 函数 然后通过这个对象调用这个函数 此时函数中this 就会指向这个 对象了
    const result =  thisArg.fn(...arg)
    delete thisArg.fn  // 删除引用
    return result  // 返回结果
}

apply

和call 差别不大 只是出入的参数不同 apply只能传入两个参数 第二个参数是一个数组

Function.prototype.myapply = function(thisArg,args) {
    const Fn =this
    thisArg = (thisArg !== null && thisArg !== undefined) 
    ? Object(thisArg)
    : window
    thisArg.fn = Fn
    const r = thisArg.fn(...args)
    //  thisArg 添加了 fn方法 会一直存在地址指向 需要删去
    delete thisArg.fn
    return r
}

bind

bind 返回的是一个函数 而且这个函数还能继续添加参数
一次调用时 传入的参数会做保留

Function.prototype.mybind = function (thisArg, ...argsArray) {

    // 1. 获取调用的函数
    const Fn = this

    thisArg = (thisArg !== null && thisArg !== undefined) ? 		
    Object(thisArg) : window

    return function (...args) {
    // 改变 this指向 
        thisArg.fn = Fn
        return thisArg.fn(...argsArray, ...args)
        // 结合所有参数
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值