手撸JS call,apply,bind

Roka 2020-05-25

call的实现

Function.prototype.Call=function(...args){
            var context=args[0]||window;
            var argArr=args.slice(1)
            context.fn=this;  //相当于给context加了一个fn属性,属性值为当前函数,在对象里面定义函数相当于把函数的this改为context对象了
            var result=context.fn(...argArr)
            delete context.fn
            return result;
    }
    var obj = {
        name: "hty",
        sex: "男"
    }
    function fn(age, pro) {
        console.log(`${this.name}是${this.sex}`)//hty是男
        console.log(`今年${age}职业是${pro}`)//今年24职业是前端攻城狮
    }
    fn.Call(obj, "24", "前端攻城狮")

apply的实现

Function.prototype.Apply=function(...args){
            var context=args[0]||window;
            var argArr=args.slice(1)
            context.fn=this;
            var result=context.fn(...argArr[0])
            delete context.fn
            return result;
    }
    var obj = {
        name: "hty",
        sex: "男"
    }
    function fn(age, pro) {
        console.log(`${this.name}是${this.sex}`)//hty是男
        console.log(`今年${age}职业是${pro}`)//今年24职业是前端攻城狮
    }
    fn.Apply(obj,["24", "前端攻城狮"])

bind的实现

Function.prototype.Bind=function(...args){
            var context=args[0]||window;
            var args=args.slice(1)
            var fbind=this;
            fBound=function(...value){   //bind要返回函数
                fbind.apply(context,args.concat(value))
            }
            return fBound
    }
    var obj = {
        name: "hty",
        sex: "男"
    }
    function fn(age, pro,type) {
        console.log(`${this.name}是${this.sex}`)//hty是男
        console.log(`今年${age}职业是${pro}他在${type}`)//今年24职业是前端攻城狮他在努力
    }
    fn.bind(obj,"24", "前端攻城狮")("努力")

相关推荐