面试中部分公司要求手写applay、call、bind,这里我就针对apply、call、bind自己写一个。
自定义apply
Function.prototype.myApply = function (context, args) {
const key = Symbol('key')
context = context || window
context[key] = this
const result = context[key](...args)
delete context[key]
return result
}
let a = {
name: 'jack',
getName: function (msg) {
return msg + this.name;
}
}
console.log("myApply", a.getName.myApply({ name: '张三' }, ['hello']))
自定义call
Function.prototype.myCall = function (context, ...args) {
const key = Symbol('key')
context = context || window
context[key] = this
const result = context[key](...args)
delete context[key]
return result
}
let a = {
name: 'jack',
getName: function (msg) {
return msg + this.name;
}
}
console.log("myApply", a.getName.myApply({ name: '张三' }, ['hello']))
自定义bind
Function.prototype.myBind = function (context, ...args) {
if (typeof this !== "function") {
throw new Error("this must be a function");
}
var self = this;
var fbound = function () {
return self.apply(this instanceof self ? this : context, args.concat(Array.prototype.slice.call(arguments)));
}
if (this.prototype) {
fbound.prototype = Object.create(this.prototype);
}
return fbound;
}
const name = a.getName.bind({ name: '张三' }, 'hello')
console.log(name())
和js中的apply、call、bind的功能完全一样。