JS中this的五大精要,基于 call / apply / bind 流氓暴力式改变this,以及使用Object改变this

this精要

1. 元素的事件绑定,事件触发,方法执行,方法中的this一般都是当前元素
2. 函数执行,看前面是否有“点”,有,“点”前面是谁this就是谁,没有,this就是window(严格模式下是undefined)
	- 匿名函数或者回调函数中的this,window居多
3. 构造函数体中的this是当前类的实例
4. 箭头函数中没有自己的this,this都是上下文中的
5. 基于 call / apply / bind 流氓暴力式改变this
let obj = {
    name: '测试',
    num: 10
};
function fn(x, y) {
    console.log(this, x + y);
}

this的Object

obj.$$ = fn;	//函数执行,看前面是否有“点”,有,“点”前面是谁this就是谁,没有,this就是window(严格模式下是undefined)
obj.$$(10, 20);

this的call

Function.prototype.call = function call(context, ...args) {
    // context -> obj
    // this -> fn
    // args -> [10,20]
    context = context == null ? window : context;
    if (!/^(object|function)$/i.test(typeof context)) {
        context = Object(context);
    }
    let result,
        key = Symbol('key');
    context[key] = this;
    result = context[key](...args);
    delete context[key];
    return result;
};
fn.call(obj, 10, 20);

this的apply

Function.prototype.apply = function call(context, args) {
    // context -> obj
    // this -> fn
    // args -> [10,20]
    context = context == null ? window : context;
    if (!/^(object|function)$/i.test(typeof context)) {
        context = Object(context);
    }
    let result,
        key = Symbol('key');
    context[key] = this;
    result = context[key](...args);
    delete context[key];
    return result;
};
fn.apply(obj, 10, 20);

this的bind

Function.prototype.bind = function bind(context, ...outerArgs) {
    // this -> fn
    // context -> obj
    // outerArgs -> [10,20]
    let _this = this;
    return function (...innerArgs) {
        _this.call(context, ...outerArgs.concat(innerArgs));
    };
};
fn.bind(obj, 10, 20)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值