一、this指向
纯函数调用--this指向window对象;
对象的方法调用--this就指向这个对象;
构造函数调用--this指向创建的实例对象;
apply,call,bind调用--this指的方法的第一个参数。
二、apply,call,bind区别
都可以改变函数的调用对象,this指的就是第一个参数;
apply(),call()返回执行后的值,bind()返回一个函数(this不能改变了,柯里化函数);
传参方式不一样,apply第二个参数接收一个数组。
fn.bind(context,arg1,arg2,arg3,...)
fn.call(context,arg1,arg2,arg3,...)
fn.apply(context,[arg1,arg2,arg3,...])
三、call、apply实现
Function.prototype.mycall = function(context,...args) {
if (typeof this !== 'function') {
throw new TypeError('not funciton')
}
if(context == null || context == undefined) {
context = window; //null、undefined指向window
}else{
context = Object(context); //非对象转换
}
context.fn = this;
let result = context.fn(...args);
delete context.fn; //调用完删除,避免污染
return result;
};
四、bind实现
Function.prototype.mybind = function(context,...args) {
const fn = this;
function fBound(...args2) {
return fn.call(this instanceof fBound ? this : context, ...args, ...args2);
};
fBound.prototype = Object.create(this.prototype);
return fBound;
};
普通调用,fBound中的this指向window,window和fBound没关系,所以返回context;
使用new,fBound中的this指向的就是新的实例,新的实例的原型链肯定有它的构造函数fBound啊,所以返回this,而忽略context,其他参数不变。