# methods 原理

# 源码

function polyfillBind(fn, ctx) {    
    function boundFn(a) {        
        var l = arguments.length;        
        return l ?
            (
                l > 1 ?
                fn.apply(ctx, arguments) :
                fn.call(ctx, a)
            ):
            fn.call(ctx)
    }
    boundFn._length = fn.length;    
    return boundFn
}

function nativeBind(fn, ctx) {    
    return fn.bind(ctx)

}

var bind = Function.prototype.bind ?
    nativeBind :
    polyfillBind;
  • methods确定上下文执行环境是通过bind绑定的。
  • 考虑到不是所有浏览器都支持bind,所以做了兼容,采用apply 和 call.

# methods 通过以下方法实现对实例的访问

function initMethods(vm, methods) {    
    for (var key in methods) {
        vm[key] = 
            methods[key] == null ? 
            noop : 
            bind(methods[key], vm);
    }
}
最后一次修改时间: 9/28/2020, 11:37:23 AM