手写call、apply、bind函数
var year = 2021 function getDate(month, day) { return this.year + '-' + month + '-' + day } Function.prototype.myCall = function (context, ...args) { // constext 如果没传入就设置为window context = context || window; // 将调用函数设置为对象方法 context.fn = this; // 调用函数 const result = context.fn(...args); // 将属性删除 delete context.fn; return result; } Function.prototype.myApply = function (context, args) { context = context || window; context.fn = this; const result = args ? context.fn(...args) : context.fn(); delete context.fn; return result; } Function.prototype.myBind = function (context, ...args) { context = context || window; const that = this; return function (...args) { context.fn = that; const result = context.fn(...args); delete context.fn; return result } } var obj = { year: 2000 } console.log('myCall', getDate.myCall(null, 3, 8)) console.log('myApply', getDate.myApply(obj, [4, 8])) console.log('myBind', getDate.myBind(obj)(3, 8))