call
Function.prototype.myCall = function (obj, ...arg) {const context = obj || window;const fn = Symbol(); // 保证唯一context[fn] = this;const res = context[fn](...arg);delete context[fn];return res;}
apply
Function.prototype.myApply = function (obj, arg) {const context = obj || window;const fn = Symbol(); // 保证唯一context[fn] = this;const res = context[fn](...arg);delete context[fn];return res;}
bind ```javascript Function.prototype.bind = function (obj, …args) { const context = obj || window; const fn = Symbol() context[fn] = this; let that = this;
const res = function(…others){
return that.apply(this instanceof that ? this : context, //new时, this指向res的实例,res继承自that[...args,...others])
}
// 如果绑定的是构造函数 那么需要继承构造函数原型属性和方法 res.prototype = Object.create(that.prototype)
return res }
// 使用 function Point(x, y) { this.x = x; this.y = y; }
Point.prototype.toString = function () { return this.x + ‘,’ + this.y; }
let YPoint = Point.bind(null, 1); let axiosPoint = new YPoint(2);
console.log(axiosPoint.toString()) // ‘1,2’ ```
