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)

猜你喜欢

转载自blog.csdn.net/qq_39453402/article/details/107923092