// call方法实现
Function.prototype.Mycall = function(context) {
if(typeof this != "function") {
throw new Error("type error")
}
context = context || window;
let arr = [...arguments].slice(1);
let result = null;
let fn = Symbol();
context[fn] = this;
result = context[fn](...arguments);
delete context.fn;
return result;
}
var obj = {
value: "vortesnail",
};
function fn() {
console.log(this.value);
}
fn.Mycall(obj); // vortesnail
// apply方法的实现
Function.prototype.Myapply = function(context) {
if(typeof this != "function") {
throw new Error("type error");
}
context = context || window;
let result = null;
let fn = Symbol();
context[fn] = this;
if(arguments[1]) {
result = context[fn](arguments[1]);
}else {
result = context[fn]();
}
delete context.fn;
return result;
}
let a = {};
let c = Symbol();
a[c] = function() {
console.log(1);
}
a[c]();
console.log(a);
// bind实现
Function.prototype.Mybind = function(context) {
if(typeof this != "function") {
throw new Error("type error");
}
let arr = [...arguments].slice(1);
let fn = this;
return function Fn() {
return fn.apply(
this instanceof Fn ? this : context,
arr.concat(...arguments)
)
}
}
console