call 和apply是在传入的上下文中直接调用相应的方法, 而bind返回的是函数, 下面为其简单实现:
call:
Function.prototype.myCall = function (){
let args = [...arguments];
let context = args.shift();
context = typeof context != 'object' ? window : context || window;
context.fn = this;
let result = context.fn(args);
delete context.fn;
return result;
}
var name = 'zhou';
let person = { 'name': 'santal'};
function sayName(str){
console.log(this.name + ' ' + str);
return this.name
}
sayName.myCall(person, 'hello'); // 'santal'
sayName('world'); // 'zhou'
sayName.myCall('你好'); // zhou // 上下文为window
apply:
Function.prototype.myApply = function (){
let args = arguments[1];
let context = arguments[0];
context = typeof context != 'object' ? window : context || window;
context.fn = this;
let result = context.fn(...args);
delete context.fn;
return result;
}
bind:
Function.prototype.myBind = function (){
let args = [...arguments];
let context = args.shift();
context = typeof context != 'object' ? window: context || window;
context.fn = this;
return function(innerArgs){ // 返回函数的参数
console.log(innerArgs)
context.fn(args);
}
}
var name = 'zhou';
var sex = 'female';
let person = { 'name': 'santal', 'sex': 'male'};
function sayName(){
console.log(this.name+ ', '+ this.sex)
}
sayName();
sayName.myBind(person, 'a', 'b')('这个世界很美好');