1、bind 可以改变绑定this指向,板顶参数
let obj = {
name: "jim",
};
function fn() {
this.say="说话";
console.log(this);
}
/***
* 1、bind 的方法可以绑定this指向, 绑定参数
* 2、返回一个绑定后的函数 (高阶函数)
* 3、如果绑定的函数被new了,当前函数的this 就是当前的实例
* 4、new出来的结果,可以找到原有类的原型
*/
Function.prototype.bind = function (context) {
let that = this;
let bindArgs = Array.prototype.slice.call(arguments, 1); //[]
function Fn(){} //Object.create() 的原理
function fBound() {
let args = Array.prototype.slice.call(arguments, 1);
return that.apply(
this instanceof fBound ? this : context,
bindArgs.concat(args)
);
}
Fn.prototype=this.prototype;
fBound.prototype=new Fn();
return fBound;
};
fn.prototype.flag='哺乳类';
let bindFn = fn.bind(obj,'猫');
let instance =new bindFn(9);
console.log(instance.flag);
2、 call 传入的数组,改变this指向
function fn1() {
console.log(1);
}
function fn2() {
console.log(2);
}
fn1.call(); //输出fn1
fn1.call.call(fn2); //输出fn2
Function.prototype.call = function (context) {
context = context ? Object(context) : window;
context.fn = this;
let args = [];
for (let i = 1; i < arguments.length; i++) {
args.push("arguments[" + i + "]");
}
// 利用数组的toString的特性
let r = eval("context.fn(" + args + ")");
delete context.fn;
return r;
};
// 如果多个call,会让call方法执行,并且会把call中的this改变成fn2;
// call 传入的是数组,apply传入的是一个个的字符串。
3、apply 传入的是字符串,改变this指向
function fn1() {
console.log(this,arguments);
}
Function.prototype.apply = function (context,args) {
context = context ? Object(context) : window;
context.fn = this;
if(!args){
return context.fn();
}
for (let i = 1; i < arguments.length; i++) {
args.push("arguments[" + i + "]");
}
// 利用数组的toString的特性
let r = eval("context.fn(" + args + ")");
delete context.fn;
return r;
};
fn1.apply('hello',[1,2,3,4]);