call
let obj = {
name: 'xxx'
}
function sayName(prev) {
console.log(prev, this.name)
}
Function.prototype.myCall = function (context) {
context = context || window;
let args = [...arguments].slice(1)
context.fn = this;
let result = context.fn(...args)
return result
}
sayName.call(obj, 'hello,')
sayName.myCall(obj, 'hello,')
apply
let obj = {
name: 'xxx'
}
function sayName(prev) {
console.log(prev, this.name)
}
Function.prototype.myApply = function (context) {
context = context || window;
let args = arguments[1]
context.fn = this;
let result = context.fn(...args)
return result
}
sayName.apply(obj, ['hello,'])
sayName.myApply(obj, ['hello,'])
bind
let obj = {
name: 'xxx'
}
function sayName(prev) {
console.log(prev, this.name)
}
Function.prototype.myBind = function (context) {
context = context || window;
let args = [...arguments].slice(1);
context.fn = this;
return function () {
context.fn(...args)
}
}
let aaa = sayName.bind(obj, 'hello,')
aaa();
let bbb = sayName.myBind(obj, 'hello,')
bbb();