原文链接: call,apply 和 bind 原生实现
上一篇: ubuntu 使用ssh登录github 避免提交时输入用户名和密码
下一篇: 浏览器帧率检测
同:都是改变 this 指向,都可接收参数
异:bind 和 call 是接收单个参数,apply 是接收数组
call
Function.prototype.newCall = function(context, ...parameter) {
context.fn = this;
context.fn(...parameter);
delete context.fn;
};
let person = {
name: "Abiel"
};
function sayHi(age, sex) {
console.log(this.name, age, sex);
}
sayHi.newCall(person, 25, "男"); // Abiel 25 男
apply
Function.prototype.newApply = function(context, parameter) {
if (typeof context === "object") {
context = context || window;
} else {
context = Object.create(null);
}
let fn = Symbol();
context[fn] = this;
context[fn](parameter);
delete context[fn];
};
bind
Function.prototype.bind = function(context, ...innerArgs) {
var me = this;
return function(...finnalyArgs) {
return me.call(context, ...innerArgs, ...finnalyArgs);
};
};
let person = {
name: "Abiel"
};
function sayHi(age, sex) {
console.log(this.name, age, sex);
}
let personSayHi = sayHi.bind(person, 25);
personSayHi("男");