首页 > 移动平台 > 详细

bind call apply 的原理

时间:2021-03-10 23:53:40      阅读:27      评论:0      收藏:0      [点我收藏+]
!function (proto) {
    function getContext(context) {
        context = context || window;
        var type = typeof context;
        if ([‘number‘, ‘string‘, ‘boolean‘, ‘null‘].includes(type)) {
            context = new context.constructor(context);
        }
        return context;
    }
    function call(context, ...args) {
        context = getContext(context);
        context._fn = this;
        let result = context._fn(...args);
        delete context._fn;
        return result;
    }
    function apply(context, args) {
        context = getContext(context);
        context._fn = this;
        let result = context._fn(...args);
        delete context._fn;
        return result;
    }

    function bind(context, ...bindArgs) {
        //  this = getName
        return (...args) => this.call(context, ...bindArgs, ...args);
    }
    proto.call = call;
    proto.apply = apply;
    proto.bind = bind;
}(Function.prototype)
function getName(age, home){
    console.log(this.name, age, home);
}
let obj = {name: ‘xiao‘}
// getName.call(obj, 10, ‘gzhou‘)



// getName.apply(obj, [11, ‘shenzhen‘])


let bindFn = getName.bind(obj, 10)
bindFn(‘北京‘)

bind call apply 的原理

原文:https://www.cnblogs.com/guangzhou11/p/14514813.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!