call apply bind
2022-05-22 本文已影响0人
Eileen_1d88
Function.prototype.myCall = function(context) {
if (context === null || context === undefined) {
context = window
}
context.fn = this
const args = Array.from(arguments).slice(1)
const result = context.fn(...args)
delete context.fn
return result
}
function A(a, b) {
this.a = a
this.b = b
return {
a: a,
b: b
}
}
A.myCall(null, 1, 2)
Function.prototype.myApply = function(context, arr = []) {
if (context === null || context === undefined) {
context = window
}
context.fn = this
const args = arr
const result = context.fn(...args)
console.log(result)
delete context.fn
return result
}
function A(a, b) {
this.a = a
this.b = b
return {
a: a,
b: b
}
}
A.myApply(null, [1, 2])
Function.prototype.myBind = function(context) {
if (context === null || context === undefined) {
context = window
}
context.fn = this
let args = Array.from(arguments).slice(1)
return function() {
args = [...args, ...arguments]
return context.fn.apply(context, args)
}
}
var obj1 = {
a: 1,
b: 2
}
var obj2 = {
a: 3,
b: 4
}
var obj3 = {
a: 5,
b: 6
}
function B() {
console.log(arguments)
console.log(this.a)
}
B.bind(obj1, 1, 2).bind(obj2, 3, 4).bind(obj3)(5, 6)
B.myBind(obj1, 1, 2).myBind(obj2, 3, 4).myBind(obj3)(5, 6)