bind - 函数绑定作用域,并返回一个函数

110 阅读1分钟

代码实现

/**
* @description: bind
* @author: huen2015
*/

// @ts-ignore
Function.prototype.bind1 = function (this: any = window, context: object, ...args: any[]) {
    const self = this
    return function (...otherArgs: any[]) {
        self.apply(context, [...args, ...otherArgs])
    }
}

function fn(this: any, name: string) {
    return 'name:' + name + '-' + 'age:' + this.age
}
export const obj = {
    age: 20
}

const bindFn = fn.bind(obj)
const bindResult = bindFn('huen2016')
console.log('bindResult', bindResult)

代码演示仓库