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;
obj.$$(10, 20);
this的call
Function.prototype.call = function call(context, ...args) {
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 = 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) {
let _this = this;
return function (...innerArgs) {
_this.call(context, ...outerArgs.concat(innerArgs));
};
};
fn.bind(obj, 10, 20)